Javascript jQuery 抓取一个上传的文件,输入类型='file'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8775295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery grab a file uploaded with input type='file'
提问by Razor Storm
I want to grab the file uploaded in a <input type='file'>
tag.
我想获取在<input type='file'>
标签中上传的文件。
When I do $('#inputId').val(), it only grabs the nameof the file, not the actual file itself.
当我做$(“#inputId”)。VAL(),它只有抓住名的文件,而不是实际的文件本身。
I'm trying to follow this:
我试图遵循这个:
http://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/
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);
}
回答by kubetz
Use event.target.files
for change
event to retrieve the File instances.
使用event.target.files
forchange
事件来检索 File 实例。
$('#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/
在这里查看更多信息: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.
此解决方案使用并非所有浏览器都支持的 File API - 请参阅http://caniuse.com/#feat=fileapi。