Javascript variable not changing inside onload function - javascript

this code always return me '3' in alert.
I select two files together (ones .mp4 format and second ones .zip format)
function readFile(input) {
var counter = input.files.length;
for(x = 0; x<counter; x++){
if (input.files && input.files[x]) {
var extension = input.files[x].name.split('.').pop().toLowerCase();
var reader = new FileReader();
reader.onload = function (e) {
urlss = 1;
if(extension == 'mp4'){
urlss = 2;
}else{
urlss = 3;
}
alert(urlss);
};
reader.readAsDataURL(input.files[x]);
}
}
}
<input type="file" id="files" name="files[]" accept=".png, .jpg, .jpeg, .zip, .mp4" onchange="readFile(this);" multiple />

That is because of var hoisting
The onload function calling after the for was ended and extension == last file extension
Try replace var with const:
function readFile(input) {
var counter = input.files.length;
for(let x = 0; x < counter; x++){
if (input.files && input.files[x]) {
const extension = input.files[x].name.split('.').pop().toLowerCase();
const reader = new FileReader();
reader.onload = function (e) {
urlss = 1;
if(extension == 'mp4'){
urlss = 2;
}else{
urlss = 3;
}
alert(urlss);
};
reader.readAsDataURL(input.files[x]);
}
}
}
Update
Please check the Webber's comment below.

Related

JQuery FileReader onload not firing

I have a multiple file uploading. When I upload the images and binding to the model as follows not firing the FileReader onload function. It skip and fire remain
Here is my code
imageSelect: function (e) {
var dataModel = bindViewModel.selected.attachments;
var reader = new FileReader();
reader.onload = function () {
var uploadImg = new Image();
uploadImg.onload = function () {
for (var i = 0; i < e.files.length; i++) {
if (e.files[i].size < 1048576) {
var attachmentName = e.files[i].name;
var attachment = { id: i, citationId: bindViewModel.selected.id, attachmentName: attachmentName, attachmentUrl: reader.result };
dataModel.push(attachment);
if (dataModel[0].attachmentName == "" && dataModel[0].attachmentUrl == "") {
dataModel.splice($.inArray(dataModel[0], dataModel), 1);
}
uploadImg.src = reader.result;
reader.readAsDataURL(e.files[i].rawFile);
}
else {
app.ShowNotifications("Error", 'The ' + e.files[i].name + ' size greater than 1MB. \r\n Maximum allowed file size is 1MB.', "error");
}
}
};
};
}
Any one can have to help me?

FileReader not working in Angular 2

I'm trying to upload an image using FileReader, It works fine in debug mode (when set breakpoint on the line this.name = Image.files[0].name;), but doesn't work if I deactivate breakpoint. testDetails.image gets set to empty string. I have tried setTimeout also, its also not working.
var fileByteArray = '';
const Image = this.AccUserImage.nativeElement;
if (Image.files && Image.files[0]) {
this.AccUserImageFile = Image.files[0];
}
var fileReader = new FileReader();
fileReader.onload = function (event) {
var imageData = fileReader.result;
var bytes = new Uint8Array(imageData);
//for (var i = 0; i < bytes.length; i++) {
for (var i = 0; i < bytes.length; ++i) {
fileByteArray += (String.fromCharCode(bytes[i]));
}
};
if (fileReader && Image.files && Image.files.length) {
fileReader.readAsArrayBuffer(Image.files[0]);
}
}
this.name = Image.files[0].name;
const ImageFile: File = this.AccUserImageFile;
let length = this.form.value.addresses.length;
this.testList = [];
for (let i = 0; i < length; i++) {
let testDetails = new testDto();
testDetails.image = btoa(fileByteArray);
}
Maybe the test should be at the end of the fileReader.load function because your test depends on fileReader.onload function to be finished at least once so fileByteArray is not undefined.
fileReader.onload = function (event) {
var imageData = fileReader.result;
var bytes = new Uint8Array(imageData);
for (var i = 0; i < bytes.length; ++i) {
fileByteArray += (String.fromCharCode(bytes[i]));
}
if (fileReader && Image.files && Image.files.length) {
fileReader.readAsArrayBuffer(Image.files[0]);
}
for (let i = 0; i < length; i++) {
let testDetails = new testDto();
testDetails.image = btoa(fileByteArray);
}
};
There were some problems in the current implementation, I am posting the working code below. The first problem was that I was using JavaScript style calling for onload function. The second problem was I have to put all the code inside onload function because readAsArrayBuffer is an async call.
var fileByteArray = '';
const Image = this.AccUserImage.nativeElement;
if (Image.files && Image.files[0]) {
this.AccUserImageFile = Image.files[0];
}
var fileReader = new FileReader();
fileReader.onload = (e) => {
var imageData = fileReader.result;
var bytes = new Uint8Array(imageData);
for (var i = 0; i < bytes.length; ++i) {
fileByteArray += (String.fromCharCode(bytes[i]));
}
this.name = Image.files[0].name;
const ImageFile: File = this.AccUserImageFile;
let length = this.form.value.addresses.length;
this.testList = [];
for (let i = 0; i < length; i++) {
testDetails.image = btoa(fileByteArray);
}
}
fileReader.readAsArrayBuffer(Image.files[0]);

How can I pass parameter when upload image?

My javascript code is like this :
for(var i=0; i < 5; i++) {
$('input[name="photo-'+i+'"]').change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageProducIsLoadedt;
reader.readAsDataURL(this.files[0]);
}
});
}
function imageProducIsLoadedt(e) {
$('#thumbnail-view-0').attr('src', e.target.result);
document.getElementById("thumbnail-upload-0").style.display = "none"
...
};
For example I click input file with name = photo-3, it will run loop on the index 3
Which I ask is : How do I send parameter i = 3 to imageProducIsLoadedt function?
I try add parameter like this :
reader.onload = imageProducIsLoadedt(e, i);
And the imageProducIsLoadedt like this :
function imageProducIsLoadedt(e,i) {
But, there exist error like this :
Uncaught ReferenceError: e is not defined
How can I solve this problem?
UPDATE
I try to update global variable like this :
let test = '';
for(let i=0; i < 5; i++) {
$('input[name="photo-'+i+'"]').change(function () {
test = i;
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageProducIsLoadedt;
reader.readAsDataURL(this.files[0]);
}
});
}
function imageProducIsLoadedt(e) {
console.log(test)
...
};
It works
You can create an anonymous function with register onload and inside that call your imageProducIsLoadedt function like below
for(var i=0; i < 5; i++) {
$('input[name="photo-'+i+'"]').change(function (e) {
if (this.files && this.files[0]) {
var reader = new FileReader();
(function(i){
reader.onload = function(){
imageProducIsLoadedt(e,i);
}
});
reader.readAsDataURL(this.files[0]);
}
});
}

Convert a Fetched data in div from excel to a query

The below code fetches data from a csv and presents in to a div as a text but am trying to convert that in to a query on fetch excel import and print then as a query
Current output when the data is imported from the excel
Example:
column1','column2','column3','column4')
column1','column2','column3','column4')
column1','column2','column3','column4')
column1','column2','column3','column4')
column1','column2','column3','column4')
Expected output
('column1','column2','column3','column4'),
('column1','column2','column3','column4'),
('column1','column2','column3','column4'),
('column1','column2','column3','column4'),
('column1','column2','column3','column4');
JS fiddle demo
HTML:
<input id = "csv" type = "file" />
<div id="result"></div>
JS:
$('#csv').change(function(e) {
if ((window.FileReader) && (e.target.files != undefined)) {
var reader = new FileReader();
reader.onload = function(e) {
var lineSplit = e.target.result.split("\n");
var content = [];
for (var j = 1; j < lineSplit.length; j++) {
var fourColumnsData = lineSplit[j].split(',').slice(0, 4).join("','");
content.push(fourColumnsData);
}
var fileContent = content.join("')<br/>");
$('#result').html(fileContent);
};
reader.readAsText(e.target.files.item(0));
}
});
Try the following
$('#csv').change(function(e) {
if ((window.FileReader) && (e.target.files != undefined)) {
var reader = new FileReader();
reader.onload = function(e) {
var lineSplit = e.target.result.split("\n");
var content = [];
for (var j = 1; j < lineSplit.length; j++) {
if (lineSplit[j].trim().length > 0) {
var fourColumnsData = "('" + lineSplit[j].split(',').slice(0, 4).join("','") + "')";
content.push(fourColumnsData);
}
}
var fileContent = content.join(",");
$('#result').html(fileContent);
};
reader.readAsText(e.target.files.item(0));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="csv" type="file" />
<div id="result"></div>

Get file name in javascript

Hi I have a input file which takes multiple files and the tag is given the Id = fileToUpload
and here goes the code:
var input = document.getElementById('filesToUpload');
for (var x = 0; x < input.files.length; x++) {
oFReader = new FileReader();
oFReader.readAsDataURL(input.files[x]);
oFReader.onload = function (oFREvent) {
imageSrc = oFREvent.target.result;
console.log("source:" +imageSrc);
name = oFREvent.target.name;
console.log("name:" +name);
};
}
Here I am able to get the source of the image but I am not able to get the name of the file which is selected for uploading. I am doing the right way or this is not a right way to get a file name.
You want to get the name from the original filelist, not the target of the FileReader's onload event. The FileReader object doesn't have a name property and the target of the onload event is the FileReader, not the file.
EDIT
Getting the name file loaded into the FileReader turns out to be kinda tricky! I came up with two ways which you can see in this fiddle.
First way just seems plain wrong - add a name property to your new FileReader() instance and then access it via evt.target. Works in FF and Chrome anyway.
var input = document.getElementById('filesToUpload');
input.addEventListener("change", soWrongButItSeemsToWork, false);
function soWrongButItSeemsToWork () {
var filelist = this.files;
for (var x = 0; x < filelist.length; x++) {
oFReader = new FileReader();
oFReader.name = filelist[x].name;
console.log("name outside:", oFReader.name);
oFReader.onload = function (oFREvent ) {
imageSrc = oFREvent.target.result;
console.log('name inside:', oFREvent.target.name);
img = document.createElement("img");
img.src = imageSrc;
document.body.appendChild(img);
};
oFReader.readAsDataURL(filelist[x]);
}
}
Use a closure as suggested by http://www.htmlgoodies.com/beyond/javascript/read-text-files-using-the-javascript-filereader.html (at the bottom). Something like:
var input2 = document.getElementById('fileinput');
input2.addEventListener("change", readMultipleFiles, false);
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) { // WOOHOO!
var dataUri = e.target.result,
img = document.createElement("img");
img.src = dataUri;
document.body.appendChild(img);
console.log( "Got the file.n"
+"name: " + f.name + "\n"
+"type: " + f.type + "\n"
+"size: " + f.size + " bytes\n"
);
};
})(f);
r.readAsDataURL(f);
}
} else {
alert("Failed to load files");
}
}
Good article on MDN here https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Try this code work perfectly:
var input = document.getElementById('filesToUpload');
for (var x = 0; x < input.files.length; x++) {
oFReader = new FileReader();
oFReader.readAsDataURL(input.files[x]);
oFReader.onload = function (oFREvent) {
imageSrc = oFREvent.target.result;
console.log("source:" +imageSrc);
name = imageSrc.replace(/^.*[\\\/]/, '');
console.log("name:" +name);
};
}
I have did a work around for this and here is the example given:
var input = document.getElementById('filesToUpload');
for (var x = 0; x < input.files.length; x++) {
oFReader = new FileReader();
oFReader.readAsDataURL(input.files[x]);
var index = 0;
oFReader.onload = function (oFREvent) {
imageSrc = oFREvent.target.result;
console.log("source:" +imageSrc);
//name = oFREvent.target.name;
name = input.files[index++].name;
console.log("name:" +name);
};
}
Each time I iterate over the reader object then I increment the index so that it indexs to the next fine in the array.

Categories

Resources