Reputation: 33691
I have this line in HTML:
<input class="input-file" type="file" id="input-recipe-pic">
After a user selects a file to upload, and presses the submit button, I am trying to get the file they selected from the file input tag above. How can I get the file with javascript so I can later send it by AJAX to avoid a page reload?
Upvotes: 1
Views: 434
Reputation: 142911
This was not possible without iframe hacks until the advent of the HTML5 File API. Using the HTML5 File API, you can do
$(".input-file").change(function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function() {
alert(reader.result);
};
reader.readAsText(file);
});
Note that this will only work on browsers that support the HTML5 File API, such as Chrome.
Upvotes: 4
Reputation: 13956
There are many upload plug in you can use for example http://blueimp.github.com/jQuery-File-Upload/
You can navigate to source code and see how it's done.
<input type="file" id="myFile" />
$('#myFile').bind('change', function() {
alert(this.files[0].size);
});
Upvotes: 1