File upload with Backbone

Viewed 17238

I'm using Backbone.js in a Rails app and I need to do file uploads as part of one of the Backbone models.

I don't believe Backbone allows for multi-part file upload out of the box. Has anyone managed to get it working via some plugin or with another external lib? How can I extend Backbone.js to support this?

5 Answers

Resurrecting this one.

As mentioned in previous answers, a multipart/form-data request can be executed via jQuery.ajax:

var formData = new FormData();
var input = document.getElementById('file');

formData.append('file', input.files[0]);

$.ajax({
  url: 'path/to/upload/endpoint'
  type:'POST',
  data: formData,
  processData: false,
  contentType: false
});

It is also important to note that, out-of-the-box, Backbone.sync will merge any options via model.save(null, { /* options here */ }) with the $.ajax instructions.

Your save procedure would look something like:

var model = new Model({
  key: 'value'
});
var input = document.getElementById('file');
var formData = new FormData();

_.each(model.keys(), function (key) { // Append your attributes
  formData.append(key, model.get(key));
});

formData.append('file', input.files[0]); // Append your file

model.save(null, {
  data: formData, 
  processData: false,
  contentType: false 
});
Related