FileReader isn't working? - javascript

this is frustrating. I've been running this code in Safari, Firefox and Chrome - all latest versions - and it doesn't work. Is it working for anyone else? I'm getting my file reference from <input type='file' id='file' name='file'>
console.log("Have now created a new file reader and it looks like this..." + reader);
reader.onload = function() {
var contents = event.target.result;
console.log("File contents: " + contents );
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(file);
}, false);
What am i doing wrong?
Thanks,
J.Wells

What am i doing wrong?
You seem to have forgotten the event parameter of the onload handler. Instead of using event.target, you also might just use reader.
Also, in the fiddle you are creating the FileReader in a very odd way. You might want to read the introduction Using files from web applications at MDN.
document.getElementById("file").addEventListener("change", function(e) {
var file = e.target.files[0],
reader = new FileReader();
console.log("Have now created a new file reader and it looks like this..." + reader);
reader.onload = function(event) {
// ^^^^^
var contents = event.target.result;
console.log("File contents: " + contents );
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(file);
}, false);

Related

Javascript inline script onchange not working

i'm having a problem on making my code to adjust to my web server, because of the security purposes, all inline javascript code to my html is not allowed.
everything is already okay i'm just having a hard time converting my other code to pure javascript
Here is my existing code,,,
<label class=qrcode-text-btn><input type=file accept="image/*" capture=environment id="openQRCamera" tabindex=-1></label>
the original code is this
<label class=qrcode-text-btn><input type=file accept="image/*" capture=environment onchange="openQRCamera(this);" tabindex=-1></label>
the onchange is not working because it is inline in the html.
this function needs to open a camera and detect if there is a qr that exists.
here is what i have now on converting it.
document.querySelector("#openQRCamera").addEventListener('onchange', (node) => {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("There is no QR detected");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
});
here is the original code
function openQRCamera(node) {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("There is no QR detected");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
}
i am using this website as my source of code, everything is working fine in my localhost, but the server is just strict, and i think that's normal for all the websites.
https://www.sitepoint.com/create-qr-code-reader-mobile-website/
i just been stuck and try to do other solution like adding event listener, and append of input just by using jquery, but it's not working. thanks in advance.
The event listener you are using is faulty, instead of listenning to 'onchange' you have to listen to 'change' like so:
document.querySelector("#openQRCamera").addEventListener('change', () => {
//remove the node as parameter and get it with javascript:
var node = document.getElementById('openQRCamera');
..

Feed FileReader from server side files

I´m starting to customize/improve an old audio editor project. I can import audio tracks to my canvas VIA drag&drop from my computer. The thing is that I also would like to use audio tracks already stored in the server just clicking over a list of available tracks... instead of use the <input type="file"> tags. How can I read the server side files with a FileReader?Ajax perhaps? Thanks in advance.
This is the code for the file reader:
Player.prototype.loadFile = function(file, el) {
//console.log(file);
var reader = new FileReader,
fileTypes = ['audio/mpeg', 'audio/mp3', 'audio/wave', 'audio/wav'],
that = this;
if (fileTypes.indexOf(file.type) < 0) {
throw('Unsupported file format!');
}
reader.onloadend = function(e) {
if (e.target.readyState == FileReader.DONE) { // DONE == 2
$('.progress').children().width('100%');
var onsuccess = function(audioBuffer) {
$(el).trigger('Audiee:fileLoaded', [audioBuffer, file]);
},
onerror = function() {
// on error - show alert modal
var tpl = (_.template(AlertT))({
message: 'Error while loading the file ' + file.name + '.'
}),
$tpl = $(tpl);
$tpl.on('hide', function() { $tpl.remove() })
.modal(); // show the modal window
// hide the new track modal
$('#newTrackModal').modal('hide');
};
that.context.decodeAudioData(e.target.result, onsuccess, onerror);
}
};
// NOTE: Maybe move to different module...
reader.onprogress = function(e) {
if (e.lengthComputable) {
$progress = $('.progress', '#newTrackModal');
if ($progress.hasClass('hide'))
$progress.fadeIn('fast');
// show loading progress
var loaded = Math.floor(e.loaded / e.total * 100);
$progress.children().width(loaded + '%');
}
};
reader.readAsArrayBuffer(file);
};
return Player;
Thanks for the suggestion micronn, I managed to make a bypass without touch the original code. The code as follows is the following:
jQuery('.file_in_server').click(function()
{
var url=jQuery(this).attr('src');//Get the server path with the mp3/wav file
var filename = url.replace(/^.*[\\\/]/, '');
var path="http://localhost/test/audio/tracks/"+filename;
var file = new File([""], filename); //I need this hack because the original function recives a buffer as well as the file sent from the web form, so I need it to send at least the filename
var get_track = new XMLHttpRequest();
get_track.open('GET',path,true);
get_track.responseType="arraybuffer";
get_track.onload = function(e)
{
if (this.status == 200) //When OK
{
Audiee.Player.context.decodeAudioData(this.response,function(buffer){ //Process the audio toward a buffer
jQuery('#menu-view ul.nav').trigger('Audiee:fileLoaded', [buffer, file]); //Send the buffer & file hack to the loading function
},function(){
alert("Error opening file");
jQuery('#newTrackModal').modal('hide');
});
}
};
get_track.send();
});
After this, in the fileLoaded function, the track is added to the editor.
var name = 'Pista ' + Audiee.Collections.Tracks.getIndexCount();
track = new TrackM({buffer: audioBuffer, file: file, name: name}); //being audioBuffer my buffer, file the fake file and name the fake file name
Audiee.Collections.Tracks.add(track);
And... thats it!

Javascript: onload event not reaching for javascript's FileReader API

I need to create extract the signature of a file at the client level itself so as to positively determine its file type. Below is my file input object:
<input id="test1" type="file">
I wrote the following javascript code against it:
var fileInput = document.getElementById('test1');
fileInput.addEventListener('change', function(e) {
console.log("file selected");
var reader = new FileReader();
reader.onload = function(e) {
console.log("loaded");
var file_slice = gcUploadFile.slice(0,4);
console.log(file_slice);
var arr_buffer = reader.readAsArrayBuffer(file_slice);
console.log(arr_buffer);
}
});
Check out the fiddle for the above.
The trouble I am having is that my code does not even enters the onload fucntion.
What am i doing wrong?
Note: I am coding only using plain javascript but i am open to use Google Closure.
Why would it reach the onload handler, nothing is ever read by the FileReader.
You have to pass the file to the fileReader by reading it as something
var fileInput = document.getElementById('test1');
fileInput.addEventListener('change', function(e) {
console.log("file selected");
var reader = new FileReader();
reader.onload = function(e) {
console.log("loaded");
var file_slice = gcUploadFile.slice(0,4);
console.log(file_slice);
var arr_buffer = reader.readAsArrayBuffer(file_slice);
console.log(arr_buffer);
}
reader.readAsBinaryString(e.target.files[0]);
});

Reading a file in chrome

I am trying to write a java script to read a file in chrome and I am using the javascript debugger of chrome.
here is the script:
function myFunction()
{
alert("I am an alert box!");
var e ;
var contents;
var control = document.getElementById("myfile");
files = control.files;
console.log("Filename: " + files[0].name);
var reader = new FileReader();
reader.readAsText(files[0]);
reader.onload = function (e) {
contents = e.target.result;
};
console.log("File contents: " + contents);
console.log("I am an alert box!");console.log("I am an alert box!");
}
</script>
when i run the code the contents variable is undefined. Plenty of discussion has gone into this but i have not found a solution. I am using the --allow-file-acess-from-files option.
Now the following code works in a strange manner:
<script>
function myFunction()
{
alert("I am an alert box!");
var e ;
var contents;
var control = document.getElementById("myfile");
files = control.files;
console.log("Filename: " + files[0].name);
var reader = new FileReader();
reader.readAsText(files[0]);
reader.onload = function (e) {
contents = e.target.result ;
};
console.log(e.target.result);
console.log("I am an alert box!");console.log("I am an alert box!");
}
</script>
It throws an error which is "Uncaught TypeError: Cannot read property 'target' of undefined"
However in the watch expression window the following variables show that the file is being read.
event.target.result: "firmware file
↵:10000000782600204D4B0000B94B0000B94B000092
↵:10001000B94B0000B94B0000B94B000000000000D4
↵:10002000000000000000000000000000B94B0000CC
↵:10003000B94B000000000000B94B0000210B00008C
↵:10004000B94B0000B94B0000B94B0000B94B0000A0
↵:10005000B94B0000B94B0000B94B0000B94B000090
↵:10006000B94B0000B94B0000B94B0000B94B000080
↵:10007000B94B0000B94B0000B94B0000B94B000070
↵:10008000B94B0000B94B0000B94B0000B94B000060
and the same ouput for e.target.result and contents variable.
Why is the code behaviour is so wierd?
Kindly help me out. I am not very skilled with javascripting.
e.target will be undefined on your 2nd console.log there towards the bottom - only one is inside your onload function, and therefore has e set.
The second one is acting on the var e ; you defined at the top, which is null, and therefore e.target.result is invalid.
e: in other words, delete this line, or move it into the function:

Deleting a file in FileSystem API after read is finished?

So I'm stuck trying to figure this out.
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function (e) {
var anchor = document.createElement("a");
anchor.setAttribute('href', "data:text/tsv;charset=UTF-8," + encodeURIComponent(this.result));
anchor.setAttribute("download", "log.tsv");
anchor.innerHTML = "Download Log Now";
document.body.appendChild(anchor);
alert("Download by clicking the damn link at the bottom.");
//delete the file?
}
reader.readAsText(file);
});
So my question is how do you delete the file after it's been read? I've tried doing fileEntry.remove(function(){console.log("File Removed.")}); where the comment is but that doesn't work.
Any ideas?
You can have a look on promise-based bro-fs where this is more clean:
fs.init()
.then(() => fs.readFile('file.txt'))
.then(content => console.log(content))
.then(() => fs.unlink('file.txt'))

Categories