Backbonejs save files and form data

2019-05-31 13:06发布

I have a upload image in a form and the form data. The form data is stored in model

How to combine the form data with the file data and save the model

I am setting the model attributes and how to include the file data in the attributes. I found this link Forcing Backbone to save an attribute as a file. I could not relate it to my form

<form enctype="multipart/form-data">
  <input type="file" name="ImageData">
  <input type="text" name="UserName">
</form>

User = Backbone.Model.extend({
  readAvatar : function (file, callback) {
    var reader = new FileReader(); // File API object for reading a file locally
    reader.onload = (function (theFile, self) {
      return function (e) {
        // Set the file data correctly on the Backbone model
        self.set({avatar_file_name : theFile.name, avatar_data : fileEvent.target.result});
        // Handle anything else you want to do after parsing the file and setting up the model.
        callback();
     };
    })(file, this);
    reader.readAsDataURL(file); // Reads file into memory Base64 encoded
  }
    attribute : function(attr) {
      return Object.defineProperty(this.prototype, attr, {
        get: function() {
          return this.get(attr);
        },
        set: function(value) {
          var attrs;

          attrs = {};
          attrs[attr] = value;
          return this.set(attrs);
        }
      });
    };
});

   var form_data = form.serializeArray();

In View after form is submitted I am serializing the form data and the reading the file. Formdata is set in attribute data and the file in Imagedata before submit

this.model.data =  form_data;
var profiledata;        
if (window.FormData) {  
        profiledata = new FormData(); 
        console.log(profiledata);   
}

if (profiledata) {  
    jQuery.each($('#ImageData')[0].files, function(i, file) {
        //reader.readAsDataURL(file);  
        profiledata.append("ImageData[]", file);

    });     
}   
    this.model.ImageData = profiledata;

    //and save the data
    this.model.save

Can I save some fields as formdata and other as attributes?

Please let me know If I am wrong. Now after I submit I get error as "'append' called on an object that does not implement interface FormData."

What name should I set here avatar_file_name and avatar_data? I need to submit the form data file with fild id as ImageData

1条回答
聊天终结者
2楼-- · 2019-05-31 13:52

I had an issue like yours. You can see above the way i solve it.

var $form = $("myFormSelector");

//==> GET MODEL FROM FORM
var model = new MyBackboneModel();
var myData = null;
var ajaxOptions = {};
// Check if it is a multipart request.
if ($form.hasFile()) {
    myData = new FormData($form[0]);
    ajaxOptions = {
        type: "POST",
        data: myData,
        processData: false,
        cache: false,
        contentType: false
    };
} else {
    myData = $form.serializeObject();
}

// Save the model.
model.save(myData, $.extend({}, ajaxOptions, {
    success: function(model, data, response) {
        //==> INSERT SUCCESS
    },
    error: function(model, response) {
        //==> INSERT ERROR
    }
}));

The hasFile is a custom method that extends the JQuery functions.

$.fn.hasFile = function() {
    if ($.type(this) === "undefined")
        return false;

    var hasFile = false;
    $.each($(this).find(":file"), function(key, input) {
        if ($(input).val().length > 0) {
            hasFile = true;
        }
    });

    return hasFile;
};
查看更多
登录 后发表回答