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?
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With