Skip to content

Instantly share code, notes, and snippets.

@tanema
Created August 9, 2012 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanema/3300429 to your computer and use it in GitHub Desktop.
Save tanema/3300429 to your computer and use it in GitHub Desktop.
This a a file field for ember.js that when asked for the value it will return the filehandler with the file within, this file handler also has the ability to upload to a url
ABApp.FileField = Ember.View.extend({
classNames: ['ember-file-field'],
tagName: "input",
attributeBindings: ['type', 'value'],
value: "",
file: null,
type: "file",
fileSize: 1024000,
fileTypes: ["image/png", "image/gif", "image/jpg", "image/tif", "image/gif"],
init: function(){
this._super();
var me = this;
setTimeout(function(){
$(me.findElementInParentElement()).live('change', function(){
me.buildValue(this)
})
},1000)
},
buildValue: function(element){
var me = this;
this.set('file', element.files[0])
this.set('value', ABApp.FileHandler.create({
element: $(element),
file: element.files[0],
field: me
}))
},
validate: function(){
var file = this.get('file');
if(!file)
return 'No File';
if(file.size > this.get('fileSize'))
return "file too big"
if(this.get('fileTypes').indexOf(file.type) == -1)
return "unknown file type"
return true
}.observes('value'),
isValid: function(){
return this.validate() == true;
}
});
ABApp.FileHandler = Ember.Object.extend({
element: null,
file: null,
field: null,
upload:function(url, cb){
if(!this.get('field').isValid())
return cb({error: this.get('field').validate()})
var formData = new FormData();
formData.append( 'file', this.get('file'))
$.ajax({
url: url,
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
complete: cb
});
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment