强制Backbone将属性保存为文件

3
有没有办法使用Model.set和Model.save,以一种强制Backbone将数据作为文件发送到服务器的方式(就像您使用带有标签的表单提交一样)?
1个回答

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%。



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接