Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the data of uploaded file in javascript

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?

like image 879
Dinoop Nair Avatar asked May 12 '13 08:05

Dinoop Nair


People also ask

How do you read a file in 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.

Can JavaScript access local files?

JavaScript does not have direct access to the local files due to security and privacy. By using a file input and a File reader, you can read one or multiple local files. We can offer the user the possibility to select files via a “file input” element that we can then process.


2 Answers

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> 
like image 119
Andrew Murphy Avatar answered Oct 08 '22 23:10

Andrew Murphy


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.

like image 20
Woody Avatar answered Oct 08 '22 23:10

Woody