简体   繁体   中英

Multipart or base64 for AJAX file uploads?

I'm writing a single page application with EmberJS and need to upload a few files.

I wrote a special view, that wraps the file input field and extracts the first file selected. This lets me bind the File -Object to a model-attribute.

Now I have to choose.

I can write a special file transform, that serialises the File -Object to base64 and simply PUT/POST this.

Or I can intercept the RESTAdapter methods createRecord and updateRecord to check every model for File -Objects and switch the PUT/POST requests to multipart/form-data and send it with the help of FormData

Does one of these directions pose significant problems?

I've had to evaluate the same concern for a Restful API I'm developing. In my opinion, the most ideal method would be to just use the RESTAdapter with base64 encoded data.

That being said, I had to use the multipart/form-data method in my case, because the data transfer is 30% higher when you base64 encode the file data. Since my API would be have to accept large (100MB+) files, I opted to have the POST method of the API to receive multipart form data, with the file and json data being one of the POST variables.

So, unless you need to upload large files like in my case, I'd recommend always sticking to the REST methods.

Just ran into this myself, and ended up using a simple jQuery AJAX call using the FormData object. My multi-select implementation (where one can drop multiple files at once) looks like this:

filesDidChange: function() {
  // Get FileList
  var $input = this.$('input'),
      fileList = $input.get(0).files;

  // Iterate files
  for (var i = 0; i < fileList.length; i++) {
    var file = fileList[i],
      formData = new FormData();

    // Append information to FormData instance
    formData.append('attachment[title]', file.name);
    formData.append('attachment[file]', file);
    formData.append('attachment[post_id]', this.get('post.id'));

    // Send upload request
    Ember.$.ajax({
      method: 'POST',
      url: '/attachments',
      cache: false,
      contentType: false,
      processData: false,
      data: formData,
      success: makeSuccessHandler(this),
      error: makeErrorHandler(this)
    });
  }

  // Notify
  this.container.lookup('util:notification').notify('Uploading file, please wait...');

  // Clear FileList
  $input.val(null);
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM