jQuery获取使用input type='file'上传的文件

14

我想获取在<input type='file'>标签中上传的文件。

当我使用 $('#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);
 }
2个回答

15

5
附加信息:上传的单个文件始终在 e.target.files[0] 中,在这一点上,您不需要使用 for 循环。 - Daniel W.

3
这可能是指HTML5的files属性。请参见w3和示例jsfiddle

哦,所以旧版浏览器不能使用JavaScript上传图片?遗憾:( - Razor Storm
1
您始终可以使用带有目标的常规表单到一个iframe。虽然代码不太美观,但是它能够正常工作。 - Ilia G

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接