64

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

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Karthik
  • 691
  • 1
  • 5
  • 16

6 Answers6

105

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.

HaaLeo
  • 10,065
  • 3
  • 44
  • 55
Aravind
  • 40,391
  • 16
  • 91
  • 110
  • 1
    How can I save the records that I parsed into fileReader into a hashmap in typescript? – Karthik Dec 01 '17 at 15:18
  • Do we need to remove the `FileReader` event listeners we subscribe to? – cjablonski76 Oct 11 '18 at 20:05
  • @arvind how can i read or store file content into some array,so that I can use those content into some other positon. – Vishwa Pratap Nov 12 '18 at 16:19
  • fileReader.readAsText() gives an error: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'. I have tried many solutions but nothing seems to work. What should i do? – Samarth Saxena Jan 08 '20 at 06:34
15

you pull the file out of the input and use the FileReader API

readFile(file: File) {
    var reader = new FileReader();
    reader.onload = () => {
        console.log(reader.result);
    };
    reader.readAsText(file);
}
bryan60
  • 28,215
  • 4
  • 48
  • 65
  • 2
    how can i read or store file content into some array,so that I can use those content into some other positon. – Vishwa Pratap Nov 12 '18 at 16:24
  • var lines = myReader.result.split('\n'); The line above in my answer, does just that. It splits the content of the file into an array. – katwekibs Nov 15 '19 at 13:12
12

if you want to make it as function you can do

    readFileContent(file: File): Promise<string> {
        return new Promise<string>((resolve, reject) => {
            if (!file) {
                resolve('');
            }

            const reader = new FileReader();

            reader.onload = (e) => {
                const text = reader.result.toString();
                resolve(text);

            };

            reader.readAsText(file);
        });
    }

then

const fileContent = await readFileContent(file);
Reza
  • 18,865
  • 13
  • 88
  • 163
7

For those asking how to get string data after reading it, the data is in the result property of fileReader. Check the code sample below.

    let fileString:any= "";

    uploadDocument(file) {
        let fileReader = new FileReader();
        fileReader.onloadend = (e) => {
           //console.log(myReader.result);
           // Entire file
           console.log(myReader.result);

           // By lines
           var lines = myReader.result.split('\n');
           for(var line = 0; line < lines.length; line++){
               console.log(lines[line]);
           }

           this.fileString = myReader.result;
        };

        fileReader.readAsText(this.file);
    }  
katwekibs
  • 1,342
  • 14
  • 17
1

it works, try like this..

var reader = new FileReader();
        reader.onloadend =(e) =>{
          var result = reader.result; 
              console.log(i+'/'+result)
              this.file64.push(result)
        };  
        reader.readAsDataURL(file);
achref akrouti
  • 575
  • 1
  • 6
  • 21
0

There's a modern native alternative: File implements Blob, so we can call Blob.text().

async function readText(event) {
  const file = event.target.files.item(0)
  const text = await file.text();
  
  document.getElementById("output").innerText = text
}
Max Alexander Hanna
  • 3,388
  • 1
  • 25
  • 35