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
705 views
in Technique[技术] by (71.8m points)

angular - Read a file and parse its content

I have file upload control which holds the selected file as below,

<div class="Block">
  <label id="lbl">File </label>
  <input #fileInput type='file'/>
</div>

I have a submit button as below,

<button type="button" class="btn btn-primary" 
     (click)="uploadDocument()">Upload File</button>

When I select a file and click on the upload button the file I need the contents inside the file without sending it to the server and reading from there.

Note: Type of file will be csv

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use FileReader in javascript to achieve this as its a csv file

Add a file change event to store the file in a object as below,

<div class="Block">
  <label id="lbl">Code </label>
  <input type='file' (change)="fileChanged($event)">

</div>

The function should set the file to an object which is used later

file:any;
fileChanged(e) {
    this.file = e.target.files[0];
}

When the submit button is clicked you can use the readAsText() method of FileReader in javascript to get the content as below,

uploadDocument(file) {
    let fileReader = new FileReader();
    fileReader.onload = (e) => {
      console.log(fileReader.result);
    }
    fileReader.readAsText(this.file);
}

Note: onload event will be fired after the content is read so your logic should be inside the onLoad function.


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

1.4m articles

1.4m replys

5 comments

56.8k users

...