April 4, 2012

How to get content of selected file by jQuery + Ajax

Question by user752433

I have a file upload element as hereafter:

<input type="file" id="uploadFile">

I can get the path & name of selected file by jQuery script as hereafter:

var filePath = $("#uploadFile").val();
var fileName = filePath.split('\').pop();

Could you please advise me how to get the file content (i thought it is in object or string format) and send it to server action.

Answer by Starx

First of all, you cannot get the path of an file-input element using $("#uploadFile").val();. It is a restriction by most of the modern browsers for security reasons.

Next, you have to upload the first, read the contents and throw the content back to the page using ajax.

You can use jQuery Form plugin to submit the form and grab the file contents on your backend.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!