Dav*_*nes 3 javascript backbone.js
有没有办法使用Model.set并Model.save以某种方式强制Backbone将数据作为文件发送到服务器(就像你提交带有<input type="file">标签的表单一样?
最简洁的答案是不.答案很长,有点像.
这实际上没有任何关系,Backbone而是能够在浏览器中使用AJAX文件.解决方案是使用HTML 5中的File API.下面是一个如何使用Backbone模型执行此操作的示例.
假设我们有一个User模型,我们想在该模型上保存一个头像文件.
// 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>
Run Code Online (Sandbox Code Playgroud)
现在在您的后端,您需要处理作为Base64编码数据的文件.
几个警告:
如果您需要广泛的浏览器支持,那么此解决方案可能不适合您.
Base64编码文件将使通过线路发送的数据量增加约30%.
| 归档时间: |
|
| 查看次数: |
1162 次 |
| 最近记录: |