强制Backbone将属性保存为文件

时间:2013-07-08 20:31:49

标签: javascript backbone.js

是否有办法以一种强制Backbone将数据作为文件发送到服务器的方式使用Model.setModel.save(就好像您提交的表单为{{1}标签?

1 个答案:

答案 0 :(得分:6)

简短的回答是否定的。答案很长,有点

这与Backbone没有任何关系,而是与浏览器中的AJAX文件有关。解决方案是使用HTML 5中的File API。下面是一个如何使用Backbone模型执行此操作的示例。

假设我们有一个用户模型,我们想在该模型上保存一个头像文件。

// Backbone Model JS

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

// Somewhere in your view JS

this.$("input[type='file']").change(function (event) {
  var file = e.originalEvent.target.files[0];
  userModel.readAvatar(file, userModel.save);
});

// HTML
<form><input type="file" name="avatar"/></form>

现在在你的后端你需要处理作为Base64编码数据的文件。

一些警告:

  1. 如果您需要广泛的浏览器支持,那么此解决方案可能不适合您。

  2. 对文件进行Base64编码会使通过线路发送的数据量增加约30%。