13

I am trying to create an upload form in Angular 2 ts (2.2.1), that allows the upload of e.g. a CSV file, but instead of the file being sent straight to a http service I want the file first to be validated in the browser.

So far I can already upload a file and print it in the console with this code:

  1. Html input for file upload

    <input type="file" (change)="changeListener($event)" #input />
    
  2. In my angular component I have set up the eventListner and the File reader.

    export class UploadComponent {
    
        public fileString;
    
        constructor() {
            this.fileString;
        }
    
        changeListener($event): void {
                this.readThis($event.target);
            }
    
        readThis(inputValue: any): void {
            var file: File = inputValue.files[0];
            var myReader: FileReader = new FileReader();
            var fileType = inputValue.parentElement.id;
            myReader.onloadend = function (e) {
                //myReader.result is a String of the uploaded file
                console.log(myReader.result);
    
                //fileString = myReader.result would not work, 
                //because it is not in the scope of the callback
            }
    
            myReader.readAsText(file);
        }
    }
    

This code works perfectly fine so far.

However I have not found a way to store the data from the reader in a way that allows me to access it with my angular component.

The myReader.onloadend() callback function does not have access to the component's variables. Is there some way to inject those variables?

How can I get the read data into the fileString variable in my component?

slaesh
  • 16,659
  • 6
  • 50
  • 52
kacase
  • 1,993
  • 1
  • 18
  • 27
  • The answer(https://stackoverflow.com/a/40843316/1908296) correct and exact needs for question But I want notify about this answer will give the result of file Reader as binary string not the original string value. – ahmed hamdy Mar 23 '20 at 20:03
  • check this question https://stackoverflow.com/q/47151035/1908296, if need load the the original CSV file content – ahmed hamdy Mar 23 '20 at 20:06

3 Answers3

34

Do it like this:

myReader.onloadend = (e) => {
   console.log(myReader.result);
   this.fileString = myReader.result as string;
};

So you can access your variables.

For a more detailed explanation: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

slaesh
  • 16,659
  • 6
  • 50
  • 52
  • the perfect answer – Mustafa Nov 10 '17 at 23:41
  • 1
    according to my linter, however, the result attribute of a FileReader done loading may be an ArrayBuffer OR a string. You should probably prepare for that. – bluppfisk Aug 03 '18 at 13:35
  • can you also tell how can i call function from onload function. – Code Feb 05 '21 at 05:30
  • which function? just do: this.myFunction("test"); – slaesh Feb 05 '21 at 09:02
  • 1
    @bluppfisk Yes and no. What output you get in `result` is determined by which `readAs...` method you called. Reading the docs for each read-method tells you which it is. So it is 100% safe to cast to string (or ArrayBuffer) *assuming* you know which read-method was used - and in practice this is usually known. Specifically result will be an ArrayBuffer *if* you called [readAsArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer). – AnorZaken Jul 15 '21 at 12:55
  • 1
    This was what I was looking for.. thanks slaesh :-) was grabbing holes in my haircut attempting to persist result from this.fileReader.addEventListener('load', this.handleEvent); - even looked at ngZones for assistance - pah! – Kieran Ryan Jul 06 '22 at 14:24
0

mxii's answer implicitly casts to string, which didn't work for me, maybe with the newer versions of angular it's not allowed anymore.

what did work for me was;

JSON.parse(fileReader.result as string)
emrhzc
  • 1,347
  • 11
  • 19
0

it work, try like this...

this.uploader.uploadAll = () => {
        console.log(this.uploader.queue.length)
        let fileCount: number = this.uploader.queue.length;
        if (fileCount > 0) {
            this.uploader.queue.forEach((val, i) => {
                var reader = new FileReader();
                reader.onloadend = (e) => {
                    var result = reader.result;
                    console.log(i + '/' + result)
                    this.file64.push(result)
                };
                reader.readAsDataURL(val._file);
            }
            );
        }
    }
achref akrouti
  • 575
  • 1
  • 6
  • 21