2012-01-08 75 views
12

我想抓住上传的文件<input type='file'>标签。jQuery抓取一个文件上传与输入类型='文件'

当我做$('#inputId')。val()时,它只抓取文件的名称,而不是实际的文件本身。

我想按照这个:

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); 
} 

回答

13

使用event.target.fileschange事件来检索文件的实例。

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

    for (var i = 0, file; file = files[i]; i++) { 
    console.log(file); 
    } 
}); 

看看这里的更多信息:http://www.html5rocks.com/en/tutorials/file/dndfiles/

该解决方案使用不是所有的浏览器支持的文件API - 见http://caniuse.com/#feat=fileapi

+4

附加信息:单个上传的文件总是在'e.target.files [0]'中,此时您不需要'for'循环。 – DanFromGermany 2014-03-28 13:15:12

3

这很可能是指HTML5 files属性。请参阅w3和样本jsfiddle

+0

嗯,所以JavaScript图像上传不可能与旧的浏览器?耻辱:( – 2012-01-08 05:17:09

+1

)你总是可以使用一个规则的表单,目标是一个iframe,它不太适合编码,但可以工作。 – 2012-01-08 05:20:49

相关问题