Javascript – jQuery grab a file uploaded with input type=’file’


I want to grab the file uploaded in a <input type='file'> tag.

When I do $('#inputId').val(), it only grabs the name of the file, not the actual file itself.

I'm trying to follow this:

function upload(file) {

  // file is from a <input> tag or from Drag'n Drop
  // Is the file an image?

  if (!file || !file.type.match(/image.*/)) return;

  // It is!
  // Let's build a FormData object

  var fd = new FormData();
  fd.append("image", file); // Append the file
  fd.append("key", "6528448c258cff474ca9701c5bab6927");
  // Get your own key:

  // Create the XHR (Cross-Domain XHR FTW!!!)
  var xhr = new XMLHttpRequest();"POST", ""); // Boooom!
  xhr.onload = function() {
    // Big win!
    // The URL of the image is:
   // Ok, I don't handle the errors. An exercice for the reader.
   // And now, we send the formdata

Best Solution

Use for change event to retrieve the File instances.

$('#inputId').change(function(e) {
  var files =; 

  for (var i = 0, file; file = files[i]; i++) {

Have a look here for more info:

This solution uses File API which is not supported by all browser - see .