FileReader not reading file properly - javascript

I ran the following function with a valid file object but it didn't work. The read text was an empty string. However, when I run the same commands via the console, it does work.
function(file) {
console.log(file)
var reader = new FileReader();
reader.readAsText(file);
console.log(reader.readyState);
console.log(reader.result);
}
Why?

I needed to set a callback for when the reader finishes reading the file, as this is done asynchronously.
function(file) {
console.log(file)
var reader = new FileReader();
reader.onload = function() {
console.log(reader.readyState);
console.log(reader.result);
}
reader.readAsText(file);
}

Related

How to read an .AppImage from Browser

I'm trying to read an appimage from the browser's drag and drop using JS and then saving it elsewhere using node.js FS module and I've tried with all of the browsers file reader options and none of them seem to work. (they all give me a file size different than the original file)https://developer.mozilla.org/en-US/docs/Web/API/FileReader
function saveMe(readFile,filename) {
var reader = new FileReader();
// Read file into memory as UTF-16
reader.readAsBinaryString(readFile, "UTF-16");
// Handle progress, success, and errors
reader.onprogress = ()=>{};
reader.onloadend = ()=>{
//console.log(reader.readyState);
if(reader.readyState==2){
//Create File './storage/apps/'+filename, reader.result
console.log(reader.result);
fs.writeFile('./storage/apps/'+filename,reader.result,(err)=>{
if(err){
console.log("Error While reading file");
}else{
}
});
}else{
}
};
reader.onerror = ()=>{console.log("Error reading file")};
}
Which method should I use?
- FileReader.readAsArrayBuffer()
- FileReader.readAsBinaryString()
- FileReader.readAsDataURL()
- FileReader.readAsText()
Read as UTF-16 and convert it to base64 when writing, also set the write options encoding to base64
function saveMe(readFile,filename) {
var reader = new FileReader();
// Read file into memory as UTF-16
reader.readAsBinaryString(readFile, "UTF-16");
// Handle progress, success, and errors
reader.onprogress = ()=>{};
reader.onloadend = ()=>{
//console.log(reader.readyState);
if(reader.readyState==2){
//Create File './storage/apps/'+filename, reader.result
//console.log(reader.result);
fs.writeFile('./storage/apps/'+filename,window.btoa(reader.result),{encoding: "base64"},(err)=>{
if(err){
console.log("Error While reading file");
}else{
}
});
}else{
}
};
reader.onerror = ()=>{console.log("Error reading file")};
}

Javascript Downloading and reading file contents from Dropbox

I am trying to download a file I uploaded as test to Dropbox. The download function works and I am getting the fileblob as well but having trouble to actually read the file contents
function downloadFile() {
dbx.filesDownload({path: '/_bk_test/test3.json'})
.then(function(response) {
var blob = response.fileBlob;
var reader = new FileReader();
reader.addEventListener("loadend", function() {
console.log(reader.result); // will print out file content
});
reader.readAsText(blob);
})
.catch(function(error) {
console.error(error);
});
}
But I am getting this error as output
Promise {<pending>}
VM215:11 TypeError: reader.addEventListener is not a function
at <anonymous>:5:24
This is strange.
But if I store the response.fileBlob in a global variable and then use the reader function, it wont show the TypeError. But I still cant read the file contents.
Either way, these are the issues
1. In a function the FileReader is throwing an exception.
2. Outside the function, the FileReader is not showing the file contents.
PS - Testing in Cordova
Alright, Cordova has a different API
function downloadFile() {
dbx.filesDownload({path: '/_bk_test/test3.json'})
.then(function(response) {
var blob = response.fileBlob;
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("read success");
console.log(evt.target.result);
};
reader.readAsText(blob);
})
.catch(function(error) {
console.error(error);
});
}

Filereader JS API not reading files properly

I have written the following code to read text from any csv or text file. However it sometimes reads successfully and stores in the variable and sometimes doesn't. Is there something missing in my code.
groupCsvData = [];
$('#add-group-upload').change(function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
groupCsvData = [text];
};
reader.readAsText(file);
)};

How to get the filename from the Javascript FileReader?

I'm using the Javascript FileReader to load an image in the browser:
e = e.originalEvent;
e.dataTransfer.dropEffect = 'copy';
this.documentFile = e.dataTransfer.files[0];
var reader = new FileReader();
reader.onloadend = function () {
if (reader.result) {
console.log(reader);
$('#theImage').attr('src', reader.result);
}
};
reader.readAsDataURL(this.documentFile);
This works fine. I now want to get the original filename of the image, but I've got no clue how and looking around the internet I can't find anything either?
Does anybody know how I can get the filename through the FileReader? All tips are welcome!
This is prob not the best solution, BUT it worked for me.
var reader = new FileReader();
reader.fileName = file.name // file came from a input file element. file = el.files[0];
reader.onload = function(readerEvt) {
console.log(readerEvt.target.fileName);
};
Not the best answer, but a working one.
I just faced the same issue, here's how I fixed it:
Using FileReader
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // event is from the HTML input
console.log(event.target.files[0].name);
The selected answer will work, but I personally prefer to prevent assigning unknown properties to existing objects.
What I do is using the built-in Map object to store connections between FileReader and its File. It works great, because Map allows the key to be anything, even an object.
Consider this example with drag&drop on the window, where multiple files can be dropped at the same time:
// We will store our FileReader to File connections here:
const files = new Map();
window.addEventListener('drop', e => {
e.preventDefault();
for (const file of e.dataTransfer.files) {
const reader = new FileReader();
files.set(reader, file);
reader.addEventListener('load', e => {
// Getting the File from our Map by the FileReader reference:
const file = files.get(e.target);
console.log(`The contents of ${file.name}:`);
console.log(e.target.result);
// We no longer need our File reference:
files.delete(e.target);
});
reader.readAsText(file);
}
});
window.addEventListener('dragover', e => {
e.preventDefault();
});
And voilà, we made it without altering our FileReader objects!
I got the filename and filesize through the FileReader this way
First of all, the reader is a javascript FILE API specification that is so useful to read files from disc.
In your example the file is readed by readAsDataURL.
reader.readAsDataURL(this.documentFile);
var name = this.documentFile.name;
var size = this.documentFile.size;
I tried on my site where use this.files[0] instead and worked fine to catch the name and the size with jQuery into an input element.
reader.readAsDataURL(this.files[0]);
$("#nombre").val(this.files[0].name);
$("#tamano").val(this.files[0].size);
I tried the solution of #Robo Robok but was unable to get this to work in my Angular Application. With this as inspiration I came up with the following and wonder if this is a correct approach. Me, I'm a bit skeptic because each upload gets there own FileReader
export class ImageFileUpload {
imageData: any;
imageName!: string;
fileReader!: FileReader;
}
selectedFiles!: FileList | null;
previews: Array<ImageFileUpload> = [];
uploadRenewals(event: any) { // event of html
const target = event.target as HTMLInputElement;
this.selectedFiles = target.files;
if (this.selectedFiles) {
const numberOfFiles = this.selectedFiles.length;
for (let i = 0; i < numberOfFiles; i++) {
const currentSelectedFile = this.selectedFiles[i];
const newImageFile = new ImageFileUpload();
newImageFile.imageName = currentSelectedFile.name;
newImageFile.fileReader = new FileReader();
newImageFile.fileReader.onload = (e: any) => {
newImageFile.imageData = e.target.result;
};
newImageFile.fileReader.readAsDataURL(currentSelectedFile);
this.previews.push(newImageFile);
}
}
}
}
HTML Page
<input #fileInput (change)="uploadRenewals($event)" multiple type="file">
<div class="slider">
<div *ngFor="let preview of previews; let idx = index">
<img [src]="preview.imageData" [alt]="preview.imageName">
</div>
</div>
One other way is to modify the FileReader() object instance with your own desired property. Adding a key like reader.myOwnFileName gets you access to that in the onload callback.
const reader = new FileReader();
reader.onload = function() {
console.log("Loaded file '" + reader.myOwnFileName + "' contents: ");
console.log(reader.result); // output file contents of chosen file.
};
reader.readAsText(this.files[0]); // use readAsText(), readAsDataURL() or other method.
// make your own key on the object instance:
reader.myOwnFileName = this.files[0].name;
If you want the filename to a variable:
var filename;
var reader = new FileReader();
reader.onloadend = function () {
if (reader.result) {
console.log(reader);
$('#theImage').attr('src', reader.result);
filename = reader.result;
}
};
reader.readAsDataURL(this.documentFile);
If you want it to run in a function:
var reader = new FileReader();
reader.onloadend = function () {
if (reader.result) {
console.log(reader);
$('#theImage').attr('src', reader.result);
myfunctionafter(reader.result);
}
};
reader.readAsDataURL(this.documentFile);
If you want to get the info out inside another function:
var reader = new FileReader();
var filename = reader.onloadend = function () {
if (reader.result) {
console.log(reader);
$('#theImage').attr('src', reader.result);
return reader.result;
}
};
reader.readAsDataURL(this.documentFile);
There might be a problem when your reader.onloadend might finish before the function you are running it from. Then you should do two functions and trigger the myfunctionafter(reader.result); from inside
Or you could simply get the src after
var filename = $('#theImage').attr('src');

Using Javascript FileReader with huge files

I have a problem using the Javascript FileRead trying to read huge files.
For example, I have a text file of 200mb and everytime I read this file the code stops working.
Its possible to read the text file, but for example ONLY the first 10 lines or stop reading after 10mb?
This is my code:
var file = form.getEl().down('input[type=file]').dom.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
data = e.target.result;
form.displayedData=data;
};
})(file);
reader.readAsText(file);
The e.target.result always has the whole data of the file.
What can I do here?
Thx
This will only read the first 10 mb:
var file = form.getEl().down('input[type=file]').dom.files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
form.displayedData = data;
};
reader.readAsText(file.slice(0, 10 * 1024 * 1024));

Categories