One of the cool features of HTML5 is the new File API that allows the broswer to directly interact with files on the file system. Most modern browsers that support HTML5 can use this API to perform client-side only processing without the need for a round trip to the servers or the use of ajax etc. In effect the server becomes redundant and the user experience more fluent and responsive. You can still, if you need to, perform server-side processing, but if you only want to make the file contents available to the browser then you can use the code below to do so:
Firstly, we need to add the HTML element that will allow us to access the file. On your web page (which needs to be declared as a proper HTML5 web page) add the following control somewhere in the body:
The important element is the
<input type="file" name="File Upload" id="txtFileUpload" accept=".csv" />, which is responsible for the file upload. You can see that we’ve added an
accept=".csv" property to filter the file upload to csv files only. This property can be changed to accept a large number of file types and form more details you can check the official documentation here.
<head> </head> section of your page:
upload() method is the one that handles the uploading and processing the selected file. In this case, I also use the excellent jquery-csv.js library to parse the lines into an array. In the end, the
data variable holds the contents of the file.
A sample web page with the full implementation can be found here.
I hope this post helped you implement something similar on your website or application.