强制骨干保存的属性为文件 [英] Forcing Backbone to save an attribute as a file

查看:88
本文介绍了强制骨干保存的属性为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方式,将迫使骨干力量使用 Model.set Model.save 办法将数据发送到服务器作为一个文件(如果你提交一个表单的<输入类型=文件> 标签

Is there a way to use Model.set and Model.save in a way that will force Backbone to send the data to the server as a file (as if you were submitting a form with an <input type="file"> tag?

推荐答案

简短的答案是否定的。长的答案是,排序

The short answer is no. The long answer is, sort of.

这其实没有什么关系骨干,而是即将能够AJAX在浏览器中的文件。解决的办法是使用文件API从HTML 5,下面是你会怎么做,以骨干型号的例子。

This doesn't really have anything to do with Backbone and instead is about being able to AJAX a file in the browser. The solution is to use the File API from HTML 5. Below is an example of how you would do that with a Backbone model.

假设我们有一个用户模式,我们要保存在该模型中的化身文件。

Let's assume we have a User model and we want to save an avatar file on that model.

// 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 EN $ C $光盘数据的文件。

Now on your back end you need to handle the file coming through as Base64 encoded data.

一对夫妇的警告:


  1. 如果你需要广泛的浏览器支持那么这个解决方案可能不会为你工作。

  1. If you need extensive browser support then this solution probably won't work for you.

的Base64编码文件将约30%,以增加通过线路发送的数据量。

Base64 encoding a file is going to increase the amount of data sent over the wire by about 30%.

这篇关于强制骨干保存的属性为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆