Utilitário para obter o conteúdo de um arquivo de um input de tipo file.
/**
* Get local file content.
*
* @author Bruno Ziiê | eu@brunoziie.com
*/
var FileContent = function(){
var that = {};
/**
* File input Id
* @type {String}
*/
that.inputElementId = null
/**
* File list from input
* @type {Object}
*/
that.fileList = null;
/**
* First element of this.fileList
* @type {Object}
*/
that.file = null;
/**
* FileReader Instance
* @type {Object}
*/
that.reader = null;
/**
* Object constructor
*
* @param {String} inputElementId File Input id
*/
this.__constructor = function(inputElementId){
that.inputElementId = inputElementId || null;
that.reader = new FileReader();
return this;
};
/**
* Refresh storaged data from input
*
* @return {void}
*/
that.getElement = function(){
if(that.inputElementId != null) {
that.fileList = document.getElementById(that.inputElementId);
if(that.fileList != null){
if (that.fileList.files.length > 0) {
that.file = that.fileList.files[0];
};
}
}
}
/**
* Get the file content in text format
*
* @param {Function} callback Function to call when the file was loaded
* @return {void}
*/
this.getAsText = function(callback){
that.getElement();
if(that.file != null){
var blob = that.file.slice(0, that.file.size);
that.reader.readAsText(blob);
that.reader.onloadend = function(){
callback(that.reader.result);
}
}else{
callback('');
}
}
/**
* Get the file content in binary format
*
* @param {Function} callback Function to call when the file was loaded
* @return {void}
*/
this.getAsBinary = function(callback){
that.getElement();
if(that.file != null){
var blob = that.file.slice(0, that.file.size);
that.reader.readAsBinaryString(blob);
that.reader.onloadend = function(){
callback(that.reader.result);
}
}else{
callback('');
}
}
/**
* Get the file content in base64 format
*
* @param {Function} callback Function to call when the file was loaded
* @return {void}
*/
this.getAsBase64Data = function(callback){
that.getElement();
if(that.file != null){
var blob = that.file.slice(0, that.file.size);
that.reader.readAsDataURL(blob);
that.reader.onloadend = function(){
callback(that.reader.result);
}
}else{
callback('');
}
}
return this.__constructor.apply(this, arguments);
};
Uso:
var myFile = new FileContent('arquivo');
myFile.getAsBinary(function(text){
// fazer algo com o text
});