I'm trying to read a local file into an ArrayBuffer using the FileReader API, like this
let reader = new FileReader();
reader.onload = function(e) {
let arrayBuffer = new Uint8Array(reader.result);
console.log(arrayBuffer);
}
reader.readAsArrayBuffer(new File([], 'data.txt'));
But I'm getting an empty arrayBuffer
How can I read this local file as an ArrayBuffer in my browser?
Thank you.
You cannot read a file by pathname through a browser. You need to have the user interact with the file system and choose a file before you can read the content.
const readFile = e => {
const file = e.target.files[0]
let reader = new FileReader();
reader.onload = function(e) {
let arrayBuffer = new Uint8Array(reader.result);
console.log(arrayBuffer);
}
reader.readAsArrayBuffer(file);
}
document.querySelector("#fileItem").onchange=readFile
<input id="fileItem" type="file">
Related
I have a binary string (from an REST API) that is the content of a Excel file.
PK\x03\x04\x14\x00\x06\00\x00\x00���N�0\x10E�H�C�-#\b5��\x12*Q>�ēƪc[�ii����\x10B�\x15j7�\x12��{2��h�nm���ƻR\f����U^\x1B7/���%�\x17\x19�rZY�\x14\x1B#1\x19__�f�\x00�q��R4D�AJ�\x1Ah\x15\x16>����V\x11�ƹ\f�Z�9����NV ...
What I want is to put this content in a FileReader object. I tried to convert the content to blob and to use readAsBinaryString but it doesn't work.
Maybe I missed something
However, when I use an input type=file, it's works with this example
$("#input").on("change", (e) => {
selectedFile = e.target.files[0];
});
let fileReader = new FileReader();
fileReader.readAsBinaryString(selectedFile);
fileReader.onload = (event)=>{
let data = event.target.result;
let workbook = XLSX.read(data,{type:"binary"});
}
What I would like is for selectedFile to reflect the binary string and not have to go through an input type=file
Thanks for your help
You can create a Blob object from the binary string, then create a File object from the Blob and finally, create a FileReader object from the File object.
var binaryString = "PK\x03\x04\x14\x00\x06\00\x00\x00���N�0\x10E�H�C�-#\b5��\x12*Q>�ēƪc[�ii����\x10B�\x15j7�\x12��{2��h�nm���ƻR\f����U^\x1B7/���%�\x17\x19�rZY�\x14\x1B#1\x19__�f�\x00�q��R4D�AJ�\x1Ah\x15\x16>����V\x11�ƹ\f�Z�9����NV ...";
// create a Blob object
var blob = new Blob([binaryString], { type: "application/vnd.ms-excel" });
// create a File object from the Blob
var file = new File([blob], "file.xlsx");
// create a FileReader object
var reader = new FileReader();
// use the readAsArrayBuffer method to read the file
reader.readAsArrayBuffer(file);
// when the reading is done, log the result
reader.onloadend = function () {
console.log(reader.result);
};
I'm trying to download a file from a server using FileReader, when it downloads the file like download.zip, but I want to set some different file names here.
var newBlob = new Blob([blob], { type: blob.type })
var reader = new FileReader();
reader.onload = function(e){
window.location.href = reader.result ? reader.result.toString() : "";
}
reader.readAsDataURL(newBlob);
You can update the file name of what you want using the reader.fileName
var reader = new FileReader();
reader.fileName = file.name // file came from a input file element
reader.onload = function(readerEvt) {
console.log(readerEvt.target.fileName);
};
If I read a wasm file in Node with fs.readFileSync I get the file in the format I want but when I try and do the exact same thing in the browser with the file reader I somehow get the wrong format?
What is the equivalent of fs.readFileSync but in the browser?
Does fs.readFileSync treat the file as an array buffer or a Binary string or something else?
<input type="file" onchange="_readWasmFile">
and the js
_readWasmFile(event) {
const file = event.target.files[0];
let reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = () => {
this.sendWasm = reader.result;
};
}
For learning purposes, I want to use the html input tag to select a jpeg image, retrieve the File Object, load it with fileReader and use the retrieved image string (base64) to create a new blob/file.
the service can upload the original file retrieved from the input just fine. However using my newFile the file get's corrupted and the file size somehow is larger.
I figure I'm doing something wrong with the blob constructor?
I'm using angular2 in typescript
<input type="file" (change)="onFileChanged($event)">
onFileChanged(event){
if (event.target.files && event.target.files[0]) {
let file = event.target.files[0];
let newFile;
let fr = new FileReader();
fr.onload = (event:any)=>{
let base64 = event.target.result
let img = base64.split(',')[1]
let blob = new Blob([window.atob(img)],{type:'image/jpeg'})
newFile = this.blobToFile(blob,'test')
}
fr.readAsDataURL(file)
console.log(file)
console.log(newFile)
this.service.upload(newFile).subscribe()
}
}
blobToFile(blob: Blob, fileName: string): File {
let b: any = blob;
b.lastModified = moment.now();
b.lastModifiedDate = new Date();
b.name = fileName;
b.webkitRelativePath="";
return <File>blob
}
EDIT------------
After finding out that fileReader is asynchronous, i've adjusted it a little bit and indeed the problem is with the blob constructor.
loggin the both the target.result of original file and new one revealed that the base64 as been transmuted. Any ideas why?
if (event.target.files && event.target.files[0]) {
let file = event.target.files[0];
let base64: string = null;
if (/^image\//.test(file.type)) {
let reader = new FileReader();
reader.onload = (e: any) => {
console.log(e.target)
base64 = e.target.result
let img = base64.split(',')[1];
let blob = new Blob([img], { type: 'image/jpeg' })
console.log(blob);
let fr = new FileReader()
fr.onload = (event: any) => {
console.log(event.target)
}
fr.readAsDataURL(blob)
}
reader.readAsDataURL(file);
}
Modify your function like this. Because FileReader is asynchronous, to process the result, you need to do it inside the onload callback, but here, you are uploading the file outside of onload which at that point, is undefined or whatever initial value it contains.
onFileChanged(event){
if (event.target.files && event.target.files[0]) {
let file = event.target.files[0];
let newFile;
let fr = new FileReader();
fr.onload = (event:any)=>{
let base64 = event.target.result
let img = base64.split(',')[1]
let blob = new Blob([window.atob(img)],{type:'image/jpeg'})
newFile = this.blobToFile(blob,'test')
this.service.upload(newFile).subscribe()
}
fr.readAsDataURL(file)
console.log(file)
console.log(newFile) // Either prints undefined or whatever initial value it contains
}
}
I am suspecting your code:
onFileChanged(event){
if (event.target.files && event.target.files[0]) {
let file = event.target.files[0];
let newFile;
let fr = new FileReader();
fr.onload = (event:any)=>{
let base64 = event.target.result
let img = base64.split(',')[1]
let blob = new Blob([window.atob(img)],{type:'image/jpeg'})
newFile = this.blobToFile(blob,'test')
}
fr.readAsDataURL(file)
console.log(file)
console.log(newFile)
this.service.upload(newFile).subscribe()
}
}
onFileChanged(event) and (event:any), these two 'event' mean different objects. event in onFileChanged is the event object of onFileChanged. event in fr.onload is the event object of FileReader.onload. Don't you think it is confusing and might cause cross reference?
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');