Problems with saving values to array using FileReader

filereader example javascript
javascript filereader base64
filereader readastext
filereader react
filereader onload
filereader readasarraybuffer
filereader readasdataurl
node filereader

I'm working on Angular4 project. I get Blob returned from my API call, then I convert it to base64 but can't manage to save it to the array of pictures (so I can show it with *ngFor later).

Here is my API call:

getImg(): Observable<Blob> { const path = *can't show this part*; return this.http.get(path, { responseType: "blob" }); }

And here is what I tried so far:

This function has error at line this.images[i] = reader.result;, because it says Property 'images' does not exist on type 'FileReader'

images: Array<any> = [];

getImages(): void {
for (var i = 0; i < this.myData.length; i++) {
  this.myApiCalls.getImg()
    .subscribe(res => {
      var reader = new FileReader();
      reader.readAsDataURL(res);
      reader.addEventListener("loadend", function () {
        this.images[i] = reader.result;
      });       
    },
      err => {
        console.log(err.message)
      });
  }
}

The other thing I tried is with callbacks, but I still got error, on the same column but for different thing. It says 'this' implicitly has type 'any' because it does not have a type annotation.

getImages(): void {
for (var i = 0; i < this.myData.length; i++) {
  this.myApiCalls.getImg()
    .subscribe(res => {
      this.readImageFile(res, function(e: any) {
        this.fields[i] = e.target.result;
      });       
    },
      err => {
        console.log(err.message)
      });
  }
}

readImageFile(response: Blob, callback: any): void {
   var reader = new FileReader();
   reader.readAsDataURL(response);
   reader.onloadend = callback 
} 

So I get data returned back correctly, but the problem is I can't manage to save it to the array. If you guys are able to help me solve that problem I would be very happy. Thank you.

Why are you converting it to a base64? You can create a url from the blob with const blobUrl = URL.createObjectURL(blob) (just remember to revoke the url to free mem after it's not used with URL.revokeObjectURL(blobUrl))? I ask because it's more efficient.

But your code is failing because of a context issue (this is not what you expect). The context inside the callback is the reader object. There's a clue in the error Property 'images' does not exist on type 'FileReader' - it's showing that this is an instance of FileReader.

Edit: You should also use let on your loop i, otherwise i won't be what you expect inside the callback.

If you want to preserve the outer scope context then use an arrow function:

getImages(): void {
for (let i = 0; i < this.myData.length; i++) {
  this.myApiCalls.getImg()
    .subscribe(res => {
      var reader = new FileReader();
      reader.addEventListener("load", () => {
        this.images[i] = reader.result;
      });
      reader.readAsDataURL(res);
    },
      err => {
        console.log(err.message)
      });
  }
}

JavaTM Programming: From Problem Analysis to Program Design, We will use an array of 26 elements to perform the letter count. Because the data will be read from an input file and the output will be saved in a file, we The class FileReader contains the method read that returns the integer value of the  Although FileReader is pretty easy to use, it's advisable to always wrap it with BuffereReader, when reading a file. This is because BufferedReader uses a char buffer to simultaneously read multiple values from a character-input stream and hence reduces the number of read() calls made by the underlying FileStream.

Here is updated your code please try this once.

images: any[]= [];

getImages(): void {
for (var i = 0; i < this.myData.length; i++) {
  this.myApiCalls.getImg()
    .subscribe(res => {
      this.readImageFile(i,res);
    },
      err => {
        console.log(err.message)
      });
  }
//here iam logged console. See values saved array or not.
console.log("Print your Value here once",this.images);
}

readImageFile(indexVal:number,response: Blob): void {
      let self = this;
      var reader = new FileReader();
      reader.readAsDataURL(response);
      reader.onloadend = function () {
          self.images[indexVal] = reader.result;
        }
} 

Try this once and let me know. I hope its useful to solve your problem. I all ready worked related this function

Thanks,

Muthukumar

FileReader, The FileReader object lets web applications asynchronously read the contents user's computer, using File or Blob objects to specify the file or data to read. This event is triggered each time the reading operation encounter an error. the result attribute contains an ArrayBuffer representing the file's data. this is a part of data in a text file that i will read and place it in array and save it in another text file.. but i got problem to read empty data at the middle.. i got around 5000 data and there are a lot of empty data for no.student column. it hard for me to place 0 at every empty space before i can read properly using filereader.

Try this answer, it may be helpful https://stackoverflow.com/a/16245768/8350917

FileReader.result, The FileReader result property returns the file's contents. An appropiate string or ArrayBuffer based on which of the reading methods was used to initiate the read operation. readAsBinaryString(), The result contains the raw binary data from the file in a string. error · onabort · onload · readyState; result. There are quite a few problems with the code you have written. One of the problems is that you need to know the number of lines in your file, using the following code will not help. File inputFile=new File("Fives.txt"); int fileSize=(int)inputFile.length();

Working with files in JavaScript, Part 2: FileReader, In my previous post, I introduced using files in JavaScript, focusing specifically The FileReader type has a single job: to read data from a file and store it in a JavaScript variable. returns the file contents as an ArrayBuffer (good for binary data such as images) Code " + event.target.error.code); }; reader. It's advised to wrap a FileReader with a BufferedReader, exactly due to the performance benefits. ObjectInputStream. ObjectInputStream should only be used alongside ObjectOutputStream. What these two classes help us accomplish is to store an object (or array of objects) into a file, and then easily read from that file.

File and FileReader, FileReader is an object with the sole purpose of reading data from Blob (and hence File too) readAsArrayBuffer(blob) – read the data in binary format ArrayBuffer . The most widely used events are for sure load and error . Interactive API reference for the JavaScript FileReader Object. FileReader is used to read the contents of a Blob or File.

Java exercises: Store text file content line by line into an array , Write a Java program to store text file content line by line into an array. Sample Solution: Java Code: import java.io.BufferedReader; import  Reading file and store it into 2D array and parse it Home. Programming Forum I need to use the 2D array with the stored values in another class. 0 0.

Comments
  • hey, @HC1122 Did you tried what iam said as comment?
  • Note that I made another edit about using let @HC1122
  • I recommend you console log this in and out of the 'load' callback and make sure it's what you expect and that it has an images array
  • Hm, currently I got error self.images[indexVal] is undefined in console.log
  • did you print same like this console.log("Print your Value here once",this.images);?
  • reader.onloadend = function () { //please here first log your output has been got or not once pls. console.log("Reader Value",reader.result); self.images[indexVal] = reader.result; }
  • Karnan thank you for your help. The problem was like commented below in using var i instead of let i and because of that Indexes were not as expected.
  • ok change like that and try one more time you got as your output has been expected