使用 Ember 数据上传文件 [英] File upload with Ember data
问题描述
有人可以提供有关使用 EmberJS 和 Ember Data 实现带有文件字段的表单的代码示例或文档吗?
Can someone provide code examples or documentation on implementing a form with a file field using EmberJS and Ember Data?
我已经熟悉 Ember Data,但我不确定如何正确实现文件上传.
I'm familiar with Ember Data already but I'm not sure how to implement file-uploads correctly.
推荐答案
这是我编写的用于文件上传的 ember-data 适配器的一部分(同一服务器 - 非跨域)
Here is part of an ember-data adapter I wrote to do file uploads (same server -not cross domain)
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);
}
});
})();
它不像 IE8 那样友好,因为我使用FormData"助手来进行分段文件上传,但它是一个很好的概念证明.
It's not IE8 friendly as is because I'm using the "FormData" helper to do multipart file upload but it's a good proof of concept.
这是带有上述适配器的余烬数据模型
Here is the ember-data model to go w/ the above adapter
PersonApp.Person = DS.Model.extend({
id: DS.attr('number'),
username: DS.attr('string'),
attachment: DS.attr('string')
});
这是车把模板
<script type="text/x-handlebars" data-template-name="person">
{{view PersonApp.UploadFileView name="logo_image" contentBinding="content"}}
</script>
这是自定义余烬视图
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]);
}
}
});
如果你想看到一个完整的峰值,请查看我最近做的多文件上传示例.
If you want to see a full blown spike with this in action checkout a multi file upload example I did recently.
https://github.com/toranb/ember-file-upload
这篇关于使用 Ember 数据上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!