Skip to content

Instantly share code, notes, and snippets.

@andriybuday
Created February 29, 2016 10:27
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 andriybuday/0f34344b68064c08c19e to your computer and use it in GitHub Desktop.
Save andriybuday/0f34344b68064c08c19e to your computer and use it in GitHub Desktop.
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