Tor*_*ups 16
这是我写的文件上传的ember-data适配器的一部分(相同的服务器 - 不跨域)
DS.DjangoRESTAdapter = DS.RESTAdapter.extend({
bulkCommit: false,
createRecord: function(store, type, record) {
var root = this.rootForType(type), json = {};
var data = new FormData();
data.append('username', record.get('username'));
data.append('attachment', record.get('attachment'));
this.django_file_ajax('http://localhost:8000/people/new/', "POST", {
data: data,
context: this,
success: function(pre_json) {
json[root] = pre_json;
this.didCreateRecord(store, type, record, json);
}
});
},
django_file_ajax: function(url, type, hash) {
hash.url = url;
hash.type = type;
hash.contentType = false;
hash.processData = false;
hash.context = this;
jQuery.ajax(hash);
}
});
})();
Run Code Online (Sandbox Code Playgroud)
这不是IE8的友好,因为我使用"FormData"帮助程序来执行多部分文件上传,但它是一个很好的概念证明.
这是使用上述适配器的ember-data模型
PersonApp.Person = DS.Model.extend({
id: DS.attr('number'),
username: DS.attr('string'),
attachment: DS.attr('string')
});
Run Code Online (Sandbox Code Playgroud)
这是把手模板
<script type="text/x-handlebars" data-template-name="person">
{{view PersonApp.UploadFileView name="logo_image" contentBinding="content"}}
</script>
Run Code Online (Sandbox Code Playgroud)
这是自定义的余烬视图
PersonApp.PersonView = Ember.View.extend({
templateName: 'person'
});
PersonApp.UploadFileView = Ember.TextField.extend({
type: 'file',
attributeBindings: ['name'],
change: function(evt) {
var self = this;
var input = evt.target;
if (input.files && input.files[0]) {
var reader = new FileReader();
var that = this;
reader.onload = function(e) {
var fileToUpload = e.srcElement.result;
var person = PersonApp.Person.createRecord({ username: 'heyo', attachment: fileToUpload });
self.get('controller.target').get('store').commit();
}
reader.readAsDataURL(input.files[0]);
}
}
});
Run Code Online (Sandbox Code Playgroud)
如果你想在行动结账中看到一个完整的峰值,我最近做了一个多文件上传示例.
https://github.com/toranb/ember-file-upload
这很简单,一般步骤是:
应该注意的是,base64编码大文件有性能问题,但对于较小的图像或文本,它不会是一个问题.
您还可以将文件发送到Ember Data的"外部",并将响应(例如代表模型的JSON有效负载)推送到商店pushPayload.如果是这样,FormData或者可以使用XHR2中的其他方法.
在此处阅读有关客户端文件操作的更多信息:http: //www.html5rocks.com/en/tutorials/file/dndfiles/
在此处阅读有关XHR2和FormData文件上传的更多信息:http://www.html5rocks.com/en/tutorials/file/xhr2/
请看下面的链接.第一个链接或博客文章包含一个链接到一个工作的jsfiddle,用于处理与emberjs上传.注意我没有写博客或创建小提琴.但它应该解决你的问题.
http://devblog.hedtek.com/2012/04/brief-foray-into-html5-file-apis.html