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);
}
});
})();
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')
});
Here is the handlebars template
<script type="text/x-handlebars" data-template-name="person">
{{view PersonApp.UploadFileView name="logo_image" contentBinding="content"}}
</script>
Here is the custom ember view
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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…