Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
file-select component with Ember.JS
<input {{bind-attr accept=fileFilter}} class="file-input-hidden" type="file" />
{{action-button action='pressButton' type=type title=title icon=icon hidden=hidden disabled=disabled visible=visible}}
App.FileSelectComponent = Ember.Component.extend({
// event fired after user has selected a file
fileSelected: null,
type: 'btn-default',
title: '',
disabled: false,
visible: null,
hidden: null,
readAsType: 'text',
fileFilter: '',
typeClass: function () {
var uppercase = this.get('uppercase') === true;
return 'input-text' + (uppercase ? ' uppercase' : '');
}.property('uppercase'),
actions: {
pressButton: function() {
this.$('input').click();
}
},
setup: function () {
var self = this;
var control = this.$('input');
control.on('click.fileSelect', function () {
this.value = null; // allows loading same file twice
});
control.on('change.fileSelect', function (evt) {
var files = evt.target.files; // FileList object
var f = files[0];
if (f) {
var reader = new FileReader();
//reader.onerror = errorHandler;
// IE is such a pain. It doesn't have 'readAsBinaryString'
if (!FileReader.prototype.readAsBinaryString) {
FileReader.prototype.readAsBinaryString = function (fileData) {
var binary = "";
var pt = this;
var innerReader = new FileReader();
innerReader.onload = function (e) {
var bytes = new Uint8Array(innerReader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
//pt.result - readonly so assign binary
pt.content = binary;
$(pt).trigger('onload');
};
innerReader.readAsArrayBuffer(fileData);
};
}
reader.onload = function(e) {
var fileContents = reader.result || reader.content;
self.sendAction('fileSelected', fileContents);
};
if(self.get('readAsType') === 'text') {
reader.readAsText(f);
} else if(self.get('readAsType') === 'binary') {
reader.readAsBinaryString(f);
}
}
});
}.on('didInsertElement'),
teardown: function () {
this.$('input').off('.fileSelect');
}.on('willDestroyElement')
});
{{file-select
title="Import Excel"
fileSelected='importAction'
fileFilter=".xlsx"
readAsType='binary'
type="btn-default btn-xs"
icon="fa-sign-in"
hidden=isReadOnly}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment