get the data of uploaded file in javascript
Asked Answered
L

6

88

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?

Lift answered 12/5, 2013 at 8:1 Comment(2)
Duplicate of #5029431 and about a dozen other questions. Please use the search box next time.Dipole
Not quite. That question is about AJAX. This seems to be 'upload a file so the browser can then manipulate it'. It doesn't mention uploading it to a server.Bit
S
39

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.

Stomachache answered 12/5, 2013 at 8:36 Comment(0)
B
73

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

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="upload_file"></textarea>

<script>
function handle_file_select( evt ) {
    console.info ( "[Event] file chooser" );

    let fl_files = evt.target.files; // JS FileList object

    // use the 1st file from the list
    let fl_file = fl_files[0];

    let reader = new FileReader(); // built in API

    let display_file = ( e ) => { // set the contents of the <textarea>
        console.info( '. . got: ', e.target.result.length, e );
        document.getElementById( 'upload_file' ).innerHTML = e.target.result;
        };

    let on_reader_load = ( fl ) => {
        console.info( '. file reader load', fl );
        return display_file; // a function
        };

    // Closure to capture the file information.
    reader.onload = on_reader_load( fl_file );

    // Read the file as text.
    reader.readAsText( fl_file );
    }

// add a function to call when the <input type=file> status changes, but don't "submit" the form
document.getElementById( 'upload' ).addEventListener( 'change', handle_file_select, false );
</script>

Bit answered 15/9, 2016 at 16:15 Comment(1)
Answer updated to remove jQuery, use modern javascript, add console calls and comments, make variable names clearer. NB: previous edits / comments to this answer (thanks!) have been incorporated, but something got corrupted and they seem to have been lostBit
S
39

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.

Stomachache answered 12/5, 2013 at 8:36 Comment(0)
S
35

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>
Sleekit answered 24/6, 2019 at 13:29 Comment(1)
plunker is slow to loadObnoxious
A
14

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'))
Amiens answered 30/7, 2021 at 22:35 Comment(1)
Excellent answer, thanks!Beeman
M
2

Try This

document.getElementById('myfile').addEventListener('change', function() {


          var GetFile = new FileReader();
        
           GetFile .onload=function(){
                
                // DO Somthing
          document.getElementById('output').value= GetFile.result;
        
        
        }
            
            GetFile.readAsText(this.files[0]);
        })
    <input type="file"  id="myfile">


    <textarea id="output"  rows="4" cols="50"></textarea>
Mcclanahan answered 30/7, 2021 at 10:19 Comment(1)
There is no need to bump a old Q with a similar answer (like the one provided by others here).Amiens
R
-1

FileReaderJS can read the files for you. You get the file content inside onLoad(e) event handler as e.target.result.

Raucous answered 11/10, 2018 at 9:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.