HTML5 File API: FileReader object is undefined after an error occured - javascript

I use Chrome 12 on Mac OS X and I've included jQuery 1.6.1 within the document.
I try to read a File with the following code, an error seams to occur while reading the file, so this.error.onerror() is called, but the FileReader-Object this.reader doesn't exists anymore and I can't get the error. I'm also not sure why the error occurs, it's a regular text document I want to read.
function FileHandler(files, action) {
console.log('FileHandler called.');
this.files = files;
this.reader = new FileReader();
this.action = action;
this.handle = function() {
console.log('FileHandler.handle called.');
for (var i = 0; i < this.files.length; i++) {
this.reader.readAsDataURL(files[i]);
}
}
this.upload = function() {
console.log('FileHandler.upload called.');
console.log(this.reader);
data = {
content: this.reader.result
}
console.log(data);
}
this.error = function() {
console.log('An error occurred while reading a file.');
console.log(this.reader.error);
}
this.reader.onload = this.upload;
this.reader.onerror = this.error;
}
This code creates the following console output:
http://cl.ly/0j1m3j0o3s071Y1K3A25

Inside .onerror, the this is not the same as outside because it's a new function (with a new scope).
Keep track of the this by setting it statically like this:
var _this = this; // _this won't change
this.reader.onerror = function() {
console.log('An error occurred while reading a file.');
console.log(_this.reader.error);
}

This should be the correct way to do it:
reader.onerror = function(event) {
console.error("File could not be read: " + event.target.error);
};

Related

Trouble with running function before FileReader

I've got some code running within a Vue.js component, but I get the following error:
TypeError: Cannot read property 'then' of undefined
I just want to run loadingAnimation() before the filereading, but searching on the internet for this error didn't really help me. What is the best way of doing this?
This is my code:
openFileBrowse() {
var vm = this;
var input = document.getElementById("filebutton");
if (input.files[0].type != "application/vnd.ms-excel"){
alert("You have uploaded a wrong file type. We require a .csv file not a " + input.files[0].type + " file.");
} else {
//Update loader text
vm.updateLoader('parsing csv');
//Start loadscreen
vm.loadingAnimation().then(function () {
//Start reading data
var reader = new FileReader();
var csvData = "";
var jsonData;
var iconv = require('iconv-lite');
reader.onload = function(){
csvData = iconv.decode(reader.result, 'latin1');
jsonData = vm.tsvJSON(csvData);
vm.addFiles(jsonData);
};
reader.onloadend = function(){
//Go to visualization page
router.push({ name: 'Visualization' });
};
reader.readAsText(input.files[0]);
});
}
},
loadingAnimation() {
//Make loading screen visible with animation
var target = document.getElementById('loadBox');
target.classList.remove('hidden')
setTimeout(function () {
target.classList.remove('visuallyhidden');
}, 20);
}
loadingAnimation isn't an async function and doesn't explicitly return a promise, so calling it doesn't give you a promise. In fact, it doesn't have any explicit return value, so calling it will always give you undefined.
If you want it to return a promise that will be fulfilled when the timer callback is fired, you have to code it. For instance:
loadingAnimation() {
return new Promise(resolve => {
//Make loading screen visible with animation
var target = document.getElementById('loadBox');
target.classList.remove('hidden')
setTimeout(function () {
target.classList.remove('visuallyhidden');
resolve();
}, 20);
});
}

Comparaison between different input files in javascript, cannot reach global variable

I'm trying to open different JSON files and compare each others values.
To do it, I used this to read the files. But I'm trying to save every data in a global variable 'data'. I think it's a asynchronous mistake but I'm pretty new to javascript and I didn't understand where the error come from.
Here is my code :
var data = {}
function readmultifiles(files) {
var reader = new FileReader();
function readFile(index) {
if( index >= files.length ) return;
var file = files[index];
reader.onload = function(e) {
// get file content
var bin = e.target.result;
bin = JSON.parse(bin);
for(task in bin['values']){
addData(bin['info']['date'],task,bin['values'][task]);
}
// do sth with bin
readFile(index+1);
}
reader.readAsBinaryString(file);
}
readFile(0);
console.log("readmultifiles");
console.log(data);
return data;
}
function addData(date, task, value){
if(data[task] == undefined){
data[task] = {};
}
data[task][date] = value;
}
var fileInput = document.querySelector('#file');
fileInput.addEventListener('change', function() {
console.log(fileInput);
var files = fileInput.files;
readmultifiles(files);
console.log("index");
console.log(data);
console.log(data['task_1']); // I can't display this object because 'undefinned'
});
What happens? When I'm trying to watch 'data', firefox console display me the object but I cannot watch inside the object.
Firefox display
What do I need to do to make a good solution. Should I use timers to wait?

uploading files in js

i'm using below method to upload files to laravel backend
setFile(id, e) {
let self = this;
let reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onload = function () {
console.log(reader.result);
self.documentArray.forEach(function (element) {
if (id == element.id && reader.result) {
element.file = reader.result;
element.file_browse_name = e.target.files[0].name;
}
});
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
},
but when i select a file larger than 5mb or around, it doesn't add the element to the relevant object of the documentArray but it logs the result in console, so i cant add validation on backend. please give me a way to solve this problem
Maybe the problem is with your PHP settings. Check your upload_max_filesize and your post_max_size

TypeError: Cannot call method 'then' of undefined at Object.Parse.File.save

I am using the js api for parse.com from an Angular js app. I am trying to save / update the profile picture of the user. I've got the following code:
Some html . . .
<input type="file" capture="camera" accept="image/*" id="profilePhotoFileUpload">
Thansk to google i/o and raymond and parse js guide
code in my controller:
$scope.updateUserProfile = function (user) {
var fileUploadControl = $("#profilePhotoFileUpload")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.jpg";
var parseFile = new Parse.File(name, file);
parseFile.save();
}
I keep getting this error:
TypeError: Cannot call method 'then' of undefined
at Object.Parse.File.save (parse-1.2.8.js:4084:43)
when calling parseFile.save()
basically the _source is undefined . . . why?!
Thanks!
I finally work it around, since my ultimate goal was to use it with phonegap, with the info in this post. . Big thanks to Raymond Camden!
function gotPic(data) {
window.resolveLocalFileSystemURI(data, function(entry) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var byteArray = new Uint8Array(evt.target.result);
var output = new Array( byteArray.length );
var i = 0;
var n = output.length;
while( i < n ) {
output[i] = byteArray[i];
i++;
}
var parseFile = new Parse.File("mypic.jpg", output);
parseFile.save().then(function(ob) {
navigator.notification.alert("Got it!", null);
console.log(JSON.stringify(ob));
}, function(error) {
console.log("Error");
console.log(error);
});
}
reader.onerror = function(evt) {
console.log('read error');
console.log(JSON.stringify(evt));
}
entry.file(function(s) {
reader.readAsArrayBuffer(s);
}, function(e) {
console.log('ee');
});
});
}
If anyone else is working Phonegap and Parse, here is another helpful example from Raymond Camden, that takes a picture:
http://www.raymondcamden.com/2013/07/23/better-example-of-phonegap-parse-and-uploading-files
var imagedata = "";
$("#takePicBtn").on("click", function(e) {
e.preventDefault();
navigator.camera.getPicture(gotPic, failHandler,
{quality:50, destinationType:navigator.camera.DestinationType.DATA_URL,
sourceType:navigator.camera.PictureSourceType.PHOTOLIBRARY});
});
function gotPic(data) {
console.log('got here');
imagedata = data;
$("#takePicBtn").text("Picture Taken!").button("refresh");
}
and it gets saved like:
var parseFile = new Parse.File("mypic.jpg", {base64:imagedata});
console.log(parseFile);
parseFile.save().then(function() {
var note = new NoteOb();
note.set("text",noteText);
note.set("picture",parseFile);
note.save(null, {
success:function(ob) {
$.mobile.changePage("#home");
}, error:function(e) {
console.log("Oh crap", e);
}
});
cleanUp();
}, function(error) {
console.log("Error");
console.log(error);
});
Especially note the {base64:imagedata}, as this is the key for creating the parse file using string data like this.

How do I write FileReader test in Jasmine?

I'm trying to make this test work, but I couldn't get my head around how to write a test with FileReader. This is my code
function Uploader(file) {
this.file = file;
}
Uploader.prototype = (function() {
function upload_file(file, file_contents) {
var file_data = new FormData()
file_data.append('filename', file.name)
file_data.append('mimetype', file.type)
file_data.append('data', file_contents)
file_data.append('size', file.size)
$.ajax({
url: "/upload/file",
type: "POST",
data: file_contents,
contentType: file.type,
success: function(){
// $("#thumbnail").attr("src", "/upload/thumbnail");
},
error: function(){
alert("Failed");
},
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',showProgress, false);
} else {
console.log("Upload progress is not supported.");
}
return myXhr;
}
});
}
return {
upload : function() {
var self = this,
reader = new FileReader(),
file_content = {};
reader.onload = function(e) {
file_content = e.target.result.split(',')[1];
upload_file(self.file, file_content);
}
}
};
})();
And this is my test
describe("Uploader", function() {
it("should upload a file successfully", function() {
spyOn($, "ajax");
var fakeFile = {};
var uploader = new Uploader(fakeFile);
uploader.upload();
expect($.ajax.mostRecentCall.args[0]["url"]).toEqual("/upload/file");
})
});
But it never gets to reader.onload.
The problem here is the use of reader.onload which is hard to test. You could use reader.addEventListener instead so you can spy on the global FileReader object and return a mock:
eventListener = jasmine.createSpy();
spyOn(window, "FileReader").andReturn({
addEventListener: eventListener
})
then you can fire the onload callback by yourself:
expect(eventListener.mostRecentCall.args[0]).toEqual('load');
eventListener.mostRecentCall.args[1]({
target:{
result:'the result you wanna test'
}
})
This syntax changed in 2.0. Code below gives an example based on Andreas Köberle's answer but using the new syntax
// create a mock object, its a function with some inspection methods attached
var eventListener = jasmine.createSpy();
// this is going to be returned when FileReader is instantiated
var dummyFileReader = { addEventListener: eventListener };
// pipe the dummy FileReader to the application when FileReader is called on window
// this works because window.FileReader() is equivalent to new FileReader()
spyOn(window, "FileReader").and.returnValue(dummyFileReader)
// your application will do something like this ..
var reader = new FileReader();
// .. and attach the onload event handler
reader.addEventListener('load', function(e) {
// obviously this wouldnt be in your app - but it demonstrates that this is the
// function called by the last line - onloadHandler(event);
expect(e.target.result).toEqual('url');
// jasmine async callback
done();
});
// if addEventListener was called on the spy then mostRecent() will be an object.
// if not it will be null so careful with that. the args array contains the
// arguments that addEventListener was called with. in our case arg[0] is the event name ..
expect(eventListener.calls.mostRecent().args[0]).toEqual('load');
// .. and arg[1] is the event handler function
var onloadHandler = eventListener.calls.mostRecent().args[1];
// which means we can make a dummy event object ..
var event = { target : { result : 'url' } };
// .. and call the applications event handler with our test data as if the user had
// chosen a file via the picker
onloadHandler(event);
I also faced similar problem and was able to achieve it without use of addeventlistener. I had used onloadend, so below is what I did.
My ts file had below code:-
let reader = new FileReader();
reader.onloadend = function() {
let dataUrl = reader.result;
// Some working here
};
reader.readAsDataURL(blob);
My spec file (test) case code :-
let mockFileReader = {
result:'',
readAsDataURL:(blobInput)=> {
console.log('readAsDataURL');
},
onloadend:()=> {
console.log('onloadend');
}
};
spyOn<any>(window, 'FileReader').and.returnValue(mockFileReader);
spyOn<any>(mockFileReader, 'readAsDataURL').and.callFake((blobInput)=> {
// debug your running application and assign to "encodedString" whatever
//value comes actually after using readAsDataURL for e.g.
//"data:*/*;base64,XoteIKsldk......"
mockFileReader.result = encodedString;
mockFileReader.onloadend();
});
This way you have mocked the FileReader object and returned a fake call to your own "readAsDataURL". And thus now when your actual code calls "reasAsDataURL" your fake function is called in which you are assigning an encoded string in "result" and calling "onloadend" function which you had already assigned a functionality in your code (.ts) file. And hence it gets called with expected result.
Hope it helps.
I think the best way is to use the real FileReader (don't mock it), and pass in a real File or Blob. This improves your test coverage and makes your tests less brittle.
If your tests don't run in IE, you can use the File constructor, e.g.
const fakeFile = new File(["some contents"], "file.txt", {type: "text/plain"});
If you need to be compatible with IE, you can construct a Blob and make it look like a file:
const fakeFile = new Blob(["some contents"]);
fakeFile.name = "file.txt";
fakeFile.type = "text/plain";
The FileReader can read either of these objects so there is no need to mock it.
i found easiest for myself to do next.
mock blob file
run reader.onload while in test environment.
as result - i do not mock Filereader
// CONTROLLER
$scope.handleFile = function (e) {
var f = e[0];
$scope.myFile = {
name: "",
size: "",
base64: ""
};
var reader = new FileReader();
reader.onload = function (e) {
try {
var buffer = e.target.result;
$scope.myFile = {
name: f.name,
size: f.size,
base64: XLSX.arrayBufferToBase64(buffer)
};
$scope.$apply();
} catch (error) {
$scope.error = "ERROR!";
$scope.$apply();
}
};
reader.readAsArrayBuffer(f);
//run in test env
if ( typeof jasmine == 'object') {reader.onload(e)}
}
//JASMINE TEST
it('handleFile 0', function () {
var fileContentsEncodedInHex = ["\x45\x6e\x63\x6f\x64\x65\x49\x6e\x48\x65\x78\x42\x65\x63\x61\x75\x73\x65\x42\x69\x6e\x61\x72\x79\x46\x69\x6c\x65\x73\x43\x6f\x6e\x74\x61\x69\x6e\x55\x6e\x70\x72\x69\x6e\x74\x61\x62\x6c\x65\x43\x68\x61\x72\x61\x63\x74\x65\x72\x73"];
var blob = new Blob(fileContentsEncodedInHex);
blob.type = 'application/zip';
blob.name = 'name';
blob.size = 11111;
var e = {0: blob, target: {result: {}}};
$scope.handleFile(e);
expect($scope.error ).toEqual("");
});
I struggled to figure out how to test onloadend when it gets called from readAsDataURL.
Here is a dump of what I ended up with.
Production code:
loadFileDataIntoChargeback(tempFileList) {
var fileNamesAndData = [];
for (var i = 0, f; f = tempFileList[i]; i++) {
let theFile = tempFileList[i];
var reader = new FileReader();
reader.onloadend = ((theFile) => {
return (fileData) => {
var insertionIndex = this.chargeback.fileList.length;
this.chargeback.fileList.push({ FileName: theFile.name, Data: fileData.target.result, FileType: theFile.type });
this.loadFilePreviews(theFile, insertionIndex);
}
})(f);
reader.readAsDataURL(f);
}
this.fileInputPath = "";
}
Test code:
describe('when the files are loaded into the chargeback', () => {
it('loads file previews', () => {
let mockFileReader = {
target: { result: '' },
readAsDataURL: (blobInput) => {},
onloadend: () => {}
};
spyOn(chargeback, "loadFilePreviews");
spyOn(window, 'FileReader').and.returnValue(mockFileReader);
spyOn(mockFileReader, 'readAsDataURL').and.callFake((blobInput) => {
mockFileReader.onloadend({ target: { result: "data:image/jpeg;base64,/9j/4QAYRXh" } });
});
var readFileList = chargeback.getArrayFromFileInput([getImageFile1()]);
chargeback.loadFileDataIntoChargeback(readFileList);
expect(chargeback.loadFilePreviews).toHaveBeenCalled();
});
});

Categories