Search code examples
backbone.js

Backbone. Form with file upload, how to handle?


I want to organize the workflow only through the REST API. I have a form that allows to upload image (enctype="multipart/form-data"). How do I handle this form via backbone? Help me please, how I can to serialize it into JSON with a file field.

Thanks. Vitaliy


Solution

  • 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);
        }   
    });