0

I want to upload a file using the extjs6 modern toolkit. Therefor I display a MessageBox with a file chooser. How can I retrieve the selected file into a javascript object after clicking the OK button to upload it (via HTTP POST e.g.)?

this.createUploadMsgBox("File Upload", function (clickedButton) {
    if (clickedButton == 'ok') {
        console.log("file: " + file);
    }

createUploadMsgBox: function (title, callback) {
        Ext.Msg.show({
            title: title,
            width: 300,
            buttons: Ext.MessageBox.OKCANCEL,
            fn: callback,
            items: [
                {
                    xtype: 'filefield',
                    label: "File:",
                    name: 'file'
                }
            ]
        });
    }

You can rum my example here:

https://fiddle.sencha.com/#view/editor&fiddle/1kro

Peter
  • 1,679
  • 2
  • 31
  • 60
  • It would be easier (and more maintainable) if you switched from the MessageBox to a custom `Ext.Sheet` with a `form` in it; is this possible or is the `MessageBox` a fixed requirement? – Alexander Nov 21 '16 at 15:25
  • No, MessageBox isn't a fixed requirement, Ext.Sheet is possible too if that brings any advantage. – Peter Nov 21 '16 at 15:28

1 Answers1

1

You have two posible solutions.

One is to use a form, and send the file via form.submit() (use form.isValid() before the submit). You can retrieve the file in the server with a MultipartFile.

The other way is to use JS File API. In you createUploadMsgBox function:

this.createUploadMsgBox("File Upload", function (clickedButton) {
   if (clickedButton == 'ok') {
      //console.log("file: " + file);
      var filefield = Ext.ComponentQuery.query('filefield')[0];
      var file = filefield.el.down('input[type=file]').dom.files[0];
      var reader = new FileReader();
      reader.onload = (function(theFile) {
          return function(e) {
              console.log(e.target.result);
          };
      })(file);
      reader.readAsBinaryString(file);
   }
});

In the file object you have the basic info of the file, and then you will see in the console the content of the file.

Hope this helps!

Community
  • 1
  • 1
qmateub
  • 512
  • 4
  • 9