Created
August 9, 2012 02:37
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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