1

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?

Kyle
  • 32,731
  • 39
  • 134
  • 184

2 Answers2

4

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.

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
1

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);
});
James
  • 13,571
  • 6
  • 61
  • 83