82

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?

Dinoop Nair
  • 2,663
  • 6
  • 31
  • 51
  • Duplicate of http://stackoverflow.com/questions/5028931/is-it-possible-to-read-a-file-using-javascript and about a dozen other questions. Please use the search box next time. – Ray Nicholus May 12 '13 at 14:03
  • 13
    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. – Andrew Murphy Sep 15 '16 at 16:16

6 Answers6

73

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>
Vegas
  • 8,017
  • 1
  • 10
  • 14
Andrew Murphy
  • 1,336
  • 1
  • 11
  • 10
38

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.

Woody
  • 7,578
  • 2
  • 21
  • 25
33

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>
vineetvdubey
  • 95
  • 1
  • 7
Mark Lagendijk
  • 6,247
  • 2
  • 36
  • 24
13

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'))
Endless
  • 34,080
  • 13
  • 108
  • 131
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>
borma425
  • 336
  • 5
  • 17
-1

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

Slawa
  • 1,141
  • 15
  • 21