Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

javascript - Upload a File and Read Data with FileReader in Angular 2

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...