Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 957
Karthik Avatar asked Nov 30 '17 20:11

Karthik


People also ask

How to read a file html?

To read an HTML file, you can use any text editor (e.g notepad, notepad++, or any specialized HTML editor). However, if you want to see what the program looks like, you need to run it on a web browser, which is designed to read and render HTML files. Write or copy HTML into a basic text editor.

How to read in a file javascript?

To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text. // Check if the file is an image.

What is FileReader in angular?

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.


1 Answers

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.

like image 105
Aravind Avatar answered Oct 02 '22 08:10

Aravind