14

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:

http://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/

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: http://api.imgur.com/ // Create the XHR (Cross-Domain XHR FTW!!!) var xhr = new XMLHttpRequest(); xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom! xhr.onload = function() { // Big win! // The URL of the image is: JSON.parse(xhr.responseText).upload.links.imgur_page; } // Ok, I don't handle the errors. An exercice for the reader. // And now, we send the formdata xhr.send(fd); } 

2 Answers 2

15

Use event.target.files for change event to retrieve the File instances.

$('#inputId').change(function(e) { var files = e.target.files; for (var i = 0, file; file = files[i]; i++) { console.log(file); } }); 

Have a look here for more info: http://www.html5rocks.com/en/tutorials/file/dndfiles/

This solution uses File API which is not supported by all browser - see http://caniuse.com/#feat=fileapi .

Sign up to request clarification or add additional context in comments.

1 Comment

Additional information: A single uploaded file is always in e.target.files[0], at that point you don't need the for loop.
3

This is likely referring to HTML5 files property. See w3 and sample jsfiddle

2 Comments

Hm, so javascript image uploading isn't possible with older browsers? Shame :(
You can always use a regular form with target to an iframe. It is less pretty to code but works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.