JavaScript FileReader is duplicating the onload callback - javascript

The following code is driving me nuts. It picks up when a file upload input has changed and then grabs the image via FileReader. The annoying thing is, and i can't work out why, that is keeps incrementally duplicating the onload event. So the first time i select a file it fires onload once, if i select a second file with the same file input the onload fires twice, if i select a file again it fires 3 times and on like that.
var ele = document.getElementById('photo-upload');
ele.addEventListener('change',function(e){
console.log("FLE CHANGED");
var file = e.target.files[0];
var fr = new FileReader();
fr.onload = function(e){
console.log("FILE READER LOADED");
}
}

You are creating new file reader with each click on <input type="file" id="photo-upload" />.
I've modified your code:
const ele = document.getElementById('photo-upload');
const fr = new FileReader();
fr.onload = function(e){
console.log("FILE READER LOADED");
}
ele.addEventListener('change',function(e){
console.log("FLE CHANGED");
const file = e.target.files[0];
// load file with using on of fr methods
// eg.
fr.readAsArrayBuffer(file);
}
Working example:
const ele = document.getElementById('photo-upload');
const fr = new FileReader();
fr.onload = evt => {
console.log(evt.target);
console.log("FILE READER LOADED");
}
ele.addEventListener('change', evt => {
console.log("FLE CHANGED");
const file = evt.target.files[0];
fr.readAsArrayBuffer(file);
})
<input type="file" id="photo-upload" />

Related

Load a local text file in javascript

I need to read a file locally using javascript.
I know that for security reasons the possibility of doing this directly is inhibited.
Is there any way to work around this?
Furthermore, if I try to use the features of the File API specification, I can't get the "load" button to work if the button itself is not directly attached in the document.body. I would like this button to work even if attached to child type elements. Is there a solution for this?
Thank you very much
fileReader() {
console.log("FileReader Called");
var fileInput = document.getElementById('file');
var fileDisplayArea = document.getElementById('source-container');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!";
}
});
}

file content in textarea using Javascript

I want to display the content of a local file in a textarea-tag using javascript.
To do so, i found the following workaround:
<textarea id="queryContent"></textarea>
<input type="file" multiple id="queryInput">
<script>
var input = document.getElementById("queryInput");
input.addEventListener("change", function () {
Array.prototype.forEach.call(input.files, function (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
console.log("File", file.name, "starts with",
reader.result.slice(0,20));
});
reader.readAsText(file);
document.getElementById("queryContent").innerText = reader.result.toString();
});
});
</script>
The problem is i am not a pro in Javascript yet. i always get a reader.result is null error and i dont know why. I appreciate your help!
This line:
document.getElementById("queryContent").innerText = reader.result.toString();
should happen inside the callback. When the script runs this line, the FileReader has not finished his job yet and therefore reader.result is very likely to be null.
Please try this code:
var input = document.getElementById("queryInput");
input.addEventListener("change", function () {
Array.prototype.forEach.call(input.files, function (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
console.log("File", file.name, "starts with", reader.result.slice(0,20));
document.getElementById("queryContent").innerText = reader.result.toString();
});
reader.readAsText(file);
});
});
P.S.
I would recommend to remove the multiple from the input element, unless it is required, to avoid unnecessary complexity.

reading the content of BPMN file

window.onload = function () {
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function (e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
var a = reader.result;
//alert(a);
importXML(a);
}
reader.readAsText(file);
} else {
alert('file not supported');
}
});
}
I am using the above javascript code to read the content of file and its working fine for the file having extension .txt . I want my code to read the content of file having extension .bpmn . Can anybody please give me some suggestions to implement this functionality

How can I store a blob in a form and send it to the server when the clicks on submit without Ajax?

This is my function:
FileCropped.prototype.change = function () {
var obj = $(this).data("plugin.file-cropped");
var files = obj.$element[0].files;
var file;
var URL = window.URL || window.webkitURL;
var blobURL;
if (files && files.length) {
file = files[0];
console.log("I have files");
if (/^image\/\w+$/.test(file.type)) {
blobURL = URL.createObjectURL(file);
obj.$element.val('');
obj.$hidden[0].value = blobURL;
//URL.revokeObjectURL(blobURL);
} else {
window.alert('Please choose an image file.');
}
} else
{
console.log("No files?");
}
}
I am trying right now to attach the blob to an existing form input but it does not work. With the chrome debugger I see the method works fine and follow the expected path, but at the time of submit the server gets nothing.
Any hint?
Edit: of course the function has no value right now. I could just use the normal file input. The goal is to be able to manipulate the blob before attaching it to the form.
You can use FileReader to read the file as data URL
var fileReader = new FileReader();
fileReader.addEventListener('load', function () {
blobURL = fileReader.result;
obj.$hidden[0].value = blobURL;
});
fileReader.readAsDataURL(file);

HTML5 FileReader API onload event not called

I am trying to implement the FileReader API to read an audio file, but the script never gets to that point from what it seems. My function is below and the trouble is at the reader.onload = handleReaderLoad; line.
function setupFS(file) {
console.log('setupFS function entered.');
var reader = new FileReader();
console.log(reader);
reader.onload = handleReaderLoad;
}
function handleReaderLoad(evt) {
console.log(reader);
var audioSrc = $('.file-playlist table tr:nth-child(n+1) td:first-child');
console.log(audioSrc);
console.log(reader.readAsDataURL(file));
audioSrc.attr('data-src', reader.readAsDataURL(file));
}
In the console, the reader shows up with the onload event as having a function handleReaderLoad(evt) { call, but the reader, audioSrc, and reader.readAsDataURL(file) variables are never logged in the console.
What am I missing?
I've figured out how the FileReader API wants the events to be set up. The main process of using a FileReader works by creating a FileReader, then declaring any/all of its events such as the onload or the onloadend events which are shown below. The process can also be condensed into one main function.
function readFile(file) {
var audioSrc;
audioSrc = $('.file-playlist table tr:nth-child(' + n + ') td:first-child');
var progress = $('.file-playlist table tr:nth-child(' + n + ') td:last-child progress');
n++;
progress.removeAttr('value');
progress.attr('data-mod', 'true');
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
audioSrc.attr('data-src', e.target.result);
$('.file-playlist audio source').attr('data-src', e.target.result);
progress.attr('value', '100');
console.log('onload stage finished');
};
})(file);
reader.onloadend = (function() {
audioSrc.text(file.name);
});
reader.readAsDataURL(file);
}
The function works by creating a FileReader, then declaring its onload events by returning the function, and the reader is given content by reading in data at the end of the function, in this case by using the readAsDataURL() method.

Categories

Resources