有没有办法使用Model.set
and Model.save
以强制 Backbone 将数据作为文件发送到服务器的方式(就像您提交带有<input type="file">
tag?
最简洁的答案是不。长答案是,sort of.
这实际上没有任何关系Backbone
而是能够在浏览器中 AJAX 文件。解决方案是使用 HTML 5 中的文件 API。下面是如何使用Backbone
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 编码数据传入的文件。
一些警告:
如果您需要广泛的浏览器支持,那么此解决方案可能不适合您。
对文件进行 Base64 编码将使通过网络发送的数据量增加约 30%。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)