Importing CSV files using jQuery and HTML5

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.

Now, let’s add the code that will deal with the file upload. As I mentioned earlier, there are different ways to deal with the uploaded file but for this example, we will stick with client-side processing using javascript. Add the following code in the <head> </head> section of your page:

The 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]( https://github.com/evanplaice/jquery-csv/" target="_blank) 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](https://gist.github.com/cmatskas/8725a6ee4f5f1a8e1cea" target="_blank).

I hope this post helped you implement something similar on your website or application.