get the data of uploaded file in javascript

217,154

Solution 1

you can use the new HTML 5 file api to read file contents

https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

but this won't work on every browser so you probably need a server side fallback.

Solution 2

The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.

See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files

In this example, the user selects an HTML file. It is displayed in the <textarea>.

<form enctype="multipart/form-data">
<input id="upload" type=file   accept="text/html" name="files[]" size=30>
</form>

<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>

<script>
function handleFileSelect(evt) {
    let files = evt.target.files; // FileList object

    // use the 1st file from the list
    let f = files[0];
    
    let reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function(theFile) {
        return function(e) {
          
          jQuery( '#ms_word_filtered_html' ).val( e.target.result );
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsText(f);
  }

  document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>

Solution 3

The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.

function init() {
  document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}

function handleFileSelect(event) {
  const reader = new FileReader()
  reader.onload = handleFileLoad;
  reader.readAsText(event.target.files[0])
}

function handleFileLoad(event) {
  console.log(event);
  document.getElementById('fileContent').textContent = event.target.result;
}
<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
</head>

<body onload="init()">
  <input id="fileInput" type="file" name="file" />
  <pre id="fileContent"></pre>
</body>

</html>

Solution 4

There exist some new tools on the blob itself that you can use to read the files content as a promise that makes you not have to use the legacy FileReader

// What you need to listen for on the file input
function fileInputChange (evt) {
  for (let file of evt.target.files) {
    read(file)
  }
}

async function read(file) {
  // Read the file as text
  console.log(await file.text())
  // Read the file as ArrayBuffer to handle binary data
  console.log(new Uint8Array(await file.arrayBuffer()))
  // Abuse response to read json data
  console.log(await new Response(file).json())
  // Read large data chunk by chunk
  console.log(file.stream())
}

read(new File(['{"data": "abc"}'], 'sample.json'))

Share:
217,154
Dinoop Nair
Author by

Dinoop Nair

software developer @Algotree, cochin, india

Updated on October 30, 2021

Comments

  • Dinoop Nair
    Dinoop Nair over 2 years

    I want to upload a csv file and process the data inside that file. What is the best method to do so? I prefer not to use php script. I did the following steps. But this method only returns the file name instead of file path.So i didnt get the desired output.

    <form id='importPfForm'>
    <input type='file' name='datafile' size='20'>
    <input type='button' value='IMPORT' onclick='importPortfolioFunction()'/>
    </form>
    
    function importPortfolioFunction( arg ) {
        var f = document.getElementById( 'importPfForm' );
        var fileName= f.datafile.value;   
    }
    

    So how can i get the data inside that file?

  • Nir O.
    Nir O. about 3 years
    plunker is slow to load
  • Endless
    Endless almost 3 years
    There is no need to bump a old Q with a similar answer (like the one provided by others here).
  • Steve Bauman
    Steve Bauman over 2 years
    Excellent answer, thanks!
  • donatJ
    donatJ over 2 years
    Be a cooler example in 2022 without jQuery
  • Andrew Murphy
    Andrew Murphy over 2 years
    @donatJ Agree. Will update.
  • WinEunuuchs2Unix
    WinEunuuchs2Unix about 2 years
    Promise was made to remove JQuery two years ago but it's still in the code: jQuery( '#ms_word_filtered_html'