Backbone. Form with file upload, how to handle?

If you are using HTML5, you can use the readAsDataURL method from the file api to read and store it on your models.

Here's the code i use to read and store.

var Image = Backbone.Model.extend({

    readFile: function(file) {
        var reader = new FileReader();
        // closure to capture the file information.
        reader.onload = (function(theFile,that) {
            return function(e) {
                //set model
                that.set({filename: theFile.name, data: e.target.result});

            };
        })(file,this);

        // Read in the image file as a data URL.
        reader.readAsDataURL(file);
    }   
});

IMHO, you cannot serialize a file into JSON. If you need to send some data along with the file you can send them as query params with POST method.

www.example.com/upload?param1=value1&param2=value2

You could try the jquery.iframe.transport plugin.

Tags:

Backbone.Js