So I have a website where the user puts a .csv file into a website and the website extracts it into a list in JavaScript. The full code that I am doing is to compare a .csv file that the user inputs into a website with the .csv file the website currently has. I want to be able to compare the two different files outside the function that I have below.
var a = [];
function compare(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var csv = event.target.result;
var data = $.csv.toArrays(csv);
number = data.length;
for (i = 1; i < data.length; i++) {
a.push({date: data[i][0], url: data[i][5], count: data[i][6]});
};
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};
}
var para = document.createElement("p");
var node = document.createTextNode(a[0].url);
para.appendChild(node);
var element = document.getElementById("demo");
element.appendChild(para);
At the end of this code snippet, I was testing to see if I can call upon the contents of the list a. However, I keep getting an "Uncaught TypeError: Cannot read property 'url' of undefined".
The error occurs at
var node = document.createTextNode(a[0].url);"
I think the problem is the async nature of the FileReader
function compare(file, callback) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (event) {
var a = [];
var csv = event.target.result;
var data = $.csv.toArrays(csv);
number = data.length;
for (i = 1; i < data.length; i++) {
a.push({
date: data[i][0],
url: data[i][5],
count: data[i][6]
});
callback(a);
};
}
//misplaced it in the onload handler
reader.onerror = function () {
alert('Unable to read ' + file.fileName);
};
}
then need to use the callback to access a
//here compare is an async method so to use the value of a after calling compare we will have to depend on a callback
compare(e.target.files[0], function (a) {
var para = document.createElement("p");
var node = document.createTextNode(a[0].url);
para.appendChild(node);
var element = document.getElementById("demo");
element.appendChild(para);
});
Demo: Fiddle
Related
im using reader.onload event to get contents of csv file,
problem is the value displays in console.log() but not in DOM i.e via binding
dropped(event: UploadEvent) {
this.files = event.files;
console.log(this.files)
for (const droppedFile of event.files) {
// Is it a file?
if (droppedFile.fileEntry.isFile) {
const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
fileEntry.file((file: File) => {
// Here you can access the real file
console.log(droppedFile.relativePath, file);
const fileToRead = file;
const fileReader = new FileReader();
fileReader.onload = this.onFileLoad;
fileReader.readAsText(fileToRead);
console.log(this.tempval) /// undefined
});
}
}}
and onFileLoad function is as follows
onFileLoad(fileLoadedEvent) {
const textFromFileLoaded = fileLoadedEvent.target.result;
this.csvContent = textFromFileLoaded;
var allTextLines = this.csvContent.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for ( var i = 0; i < allTextLines.length; i++) {
// split content based on comma
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for ( var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}this.tempval = linesconsole.log(this.tempval) // printing value
};
unfortunately data inside this.tempval is not accessible anywhere
not in html DOM or inside dropped() funtion. except inside onFileLoad()
im just new to typescript
thanks in advance
Let's say I want to upload 2 images to an ajax, I will send them using this format
{ "base64StringName:" : "[ {"1": "base64_1"}, {"2" : "base64_2"} ]"}
So its an object that contains an array of objects of base64 strings
To do so, I will need to create an array and inside this array, I will push json objects into it.
Here is my code for this:
<script>
var test ='';
var imageArray =[];
var imageObject ={};
$('#inputFileToLoad').on('change', function(){
imageArray.length = 0;
fileCount = this.files.length;
for(i = 0; i < fileCount; i++){
var file = document.querySelector('#inputFileToLoad').files[i];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
test = reader.result.split(',')[1];
console.log(test);
imageObject[i] = test;
imageArray.push(imageObject);
};
reader.onerror = function (error) {
alert('Error: ', error);
};
}
});
$('#inputFileToLoadButton').on('click', function(){
console.log(imageArray);
$.ajax({
url:"some url",
method:"POST",
data: {
"base64String": imageArray
}
,success: function () {
swal("Success!","Upload Finished!","success");
//add redirect!
},
error: function (jqXHR) {
swal("Error",jqXHR.responseText, "error");
}
});
});
</script>
However, I encounter a problem, my first object inside the array somehow gets overwritten.
it becomes
{ "base64StringName:" : "[ {"1": "base64_2"}, {"2" : "base64_2"} ]"}
Also when i printed out the first base64 encoded file at console.log(test); it is undefined, but when i printed out the second base64 encoded file, it prints the second file only.
try this:
var test = '';
var imageArray = [];
var imageObject;
$('#inputFileToLoad').on('change', function() {
imageArray.length = 0;
fileCount = this.files.length;
for (i = 0; i < fileCount; i++) {
debugger;
var file = document.querySelector('#inputFileToLoad').files[i];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
test = this.result.split(',')[1];
imageObject = {};
imageObject[index] = test;
imageArray.push(imageObject);
}.bind({
index: i
});
reader.onerror = function(error) {
alert('Error: ', error);
};
}
});
I'm trying to make a small snippet to preview images before uploading them:
$.fn.previewImg=function($on){
var input = this;
try{
if (this.is("input[type='file']")) {
input.change(function(){
var reader = new FileReader();
reader.onloadend = function(){
for (var i = 0; i < $on.length; i++) {
if (/img/i.test($on[i].tagName)) $on[i].src = reader.result;
else $on[i].style.bakgroundImage = "url("+reader.result+")";
}
};
});
}else throw new exception("Trying to preview image from an element that is not a file input!");
}catch(x){
console.log(x);
}
};
I'm calling it like:
$("#file").previewImg($(".preview_img"));
but the onloadend function is never called.
FIDDLE
Actually , you got to specify the file and instruct the fileReader to read it.
Below is the corrected code.
$.fn.previewImg=function($on){
var input = this;
try{
if (this.is("input[type='file']")) {
input.change(function(evt){
var reader = new FileReader();
console.log("Input changed");
reader.onloadend = function(){
console.log("onloadend triggered");
for (var i = 0; i < $on.length; i++) {
if (/img/i.test($on[i].tagName)) $on[i].src = reader.result;
else $on[i].style.bakgroundImage = "url("+reader.result+")";
}
};
//get the selected file
var files = evt.target.files;
//instruct reader to read it
reader.readAsDataURL(files[0]);
});
}else throw new exception("Trying to preview image from an element that is not a file input!");
}catch(x){
console.log(x);
}
};
$("#file").previewImg($(".preview_img"));
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.
I'm using the FileReader API to read multiple files.
<html> <body>
<input type="file" id="filesx" name="filesx[]"
onchange="readmultifiles(this.files)" multiple=""/>
<div id="bag"><ul/></div>
<script>
window.onload = function() {
if (typeof window.FileReader !== 'function') {
alert("The file API isn't supported on this browser yet.");
}
}
function readmultifiles(files) {
var ul = document.querySelector("#bag>ul");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
function setup_reader(file) {
var name = file.name;
var reader = new FileReader();
reader.onload = function(e) {
var bin = e.target.result; //get file content
// do sth with text
var li = document.createElement("li");
li.innerHTML = name;
ul.appendChild(li);
}
reader.readAsBinaryString(file);
}
for (var i = 0; i < files.length; i++) { setup_reader(files[i]); }
}
</script> </body> </html>
The problem is that all files are read at the same time, and when the files have a total size (sum) that is very large, the browser crashes.
I want to read one file after another, so that the memory consumption is reduced.
Is this possible?
I came up with a solution myself which works.
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;
// do sth with bin
readFile(index+1)
}
reader.readAsBinaryString(file);
}
readFile(0);
}
I'm updating this question for the benefit of new users, who are looking for a solution to upload multiple files via the FileReader API, especially using ES.
Rather than manually iterating over each file, it's much simpler & cleaner to use Object.keys(files) in ES:
<input type="file" onChange="readmultifiles" multiple/>
<script>
function readmultifiles(e) {
const files = e.currentTarget.files;
Object.keys(files).forEach(i => {
const file = files[i];
const reader = new FileReader();
reader.onload = (e) => {
//server call for uploading or reading the files one-by-one
//by using 'reader.result' or 'file'
}
reader.readAsBinaryString(file);
})
};
</script>
This should read the files one by one:
function readmultifiles(files) {
var ul = document.querySelector("#bag>ul");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
// Read first file
setup_reader(files, 0);
}
// Don't define functions in functions in functions, when possible.
function setup_reader(files, i) {
var file = files[i];
var name = file.name;
var reader = new FileReader();
reader.onload = function(e){
readerLoaded(e, files, i, name);
};
reader.readAsBinaryString(file);
// After reading, read the next file.
}
function readerLoaded(e, files, i, name) {
// get file content
var bin = e.target.result;
// do sth with text
var li = document.createElement("li");
li.innerHTML = name;
ul.appendChild(li);
// If there's a file left to load
if (i < files.length - 1) {
// Load the next file
setup_reader(files, i+1);
}
}
Define the input using multiple property:
<input onchange = 'upload(event)' type = 'file' multiple/>
Define the upload function:
const upload = async (event) => {
// Convert the FileList into an array and iterate
let files = Array.from(event.target.files).map(file => {
// Define a new file reader
let reader = new FileReader();
// Create a new promise
return new Promise(resolve => {
// Resolve the promise after reading file
reader.onload = () => resolve(reader.result);
// Read the file as a text
reader.readAsText(file);
});
});
// At this point you'll have an array of results
let res = await Promise.all(files);
}
My complete solution is here:
<html> <body>
<input type="file" id="filesx" name="filesx[]"
onchange="readmultifiles(this.files)" multiple=""/>
<div id="bag"></div>
<script>
window.onload = function() {
if (typeof window.FileReader !== 'function') {
alert("The file API isn't supported on this browser yet.");
}
}
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;
// do sth with bin
readFile(index+1)
}
reader.readAsBinaryString(file);
}
readFile(0);
function setup_reader(file) {
var name = file.name;
var reader = new FileReader();
var ul = document.createElement("ul");
document.getElementById('bag').appendChild(ul);
reader.onload = function(e) {
var bin = e.target.result; //get file content
// do sth with text
var li = document.createElement("li");
li.innerHTML = name;
ul.appendChild(li);
}
reader.readAsBinaryString(file);
}
for (var i = 0; i < files.length; i++) { setup_reader(files[i]); }
}
</script> </body> </html>
I implemented another solution using modern JS (Map, Iterator). I adapted the code from my Angular application (originally written with some TS features).
Like Steve KACOU mentioned, we create a different FileReader instance for each file.
<input type="file" id="filesx" name="filesx[]"
onchange="processFileChange(this)" multiple=""/>
function processFileChange(event) {
if (event.target.files && event.target.files.length) {
const fileMap = new Map();
for (let i = 0; i < event.target.files.length; i++) {
const file = event.target.files[i];
const fileReader = new FileReader();
fileMap.set(fileReader, file);
}
const mapEntries = fileMap.entries();
readFile(mapEntries);
}
}
function readFile(mapEntries) {
const nextValue = mapEntries.next();
if (nextValue.done === true) {
return;
}
const [fileReader, file] = nextValue.value;
fileReader.readAsDataURL(file);
fileReader.onload = () => {
// Do black magic for each file here (using fileReader.result)
// Read the next file
readFile(mapEntries);
};
}
Basically this takes advantage of passing objects by reference to perpetuate the map with every iteration. This makes the code quite easy to read in my opinion.
Taking the best parts of these answers.
<input type="file" onchange="readmultifiles(this.files)" multiple />
<script>
function readmultifiles(files) {
for (file of files) {
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.fileName = file.name;
reader.onload = (event) => {
const fileName = event.target.fileName;
const content = event.currentTarget.result;
console.log({ fileName, content });
};
}
}
</script>
You must instantiate a FileReader for each file to read.
function readFiles(event) {
//Get the files
var files = event.input.files || [];
if (files.length) {
for (let index = 0; index < files.length; index++) {
//instantiate a FileReader for the current file to read
var reader = new FileReader();
reader.onload = function() {
var result = reader.result;
console.log(result); //File data
};
reader.readAsDataURL(files[index]);
}
}
}
Try this
const setFileMultiple = (e) => {
e.preventDefault();
//Get the files
let file = [...e.target.files] || [];
file.forEach((item, index) => {
let reader = new FileReader();
reader.onloadend = () => {
console.log("result", reader.result);
};
reader.readAsDataURL(file[index]);
});
};