繁体   English   中英

jQuery抓取一个用input type ='file'上传的文件

[英]jQuery grab a file uploaded with input type='file'

我想抓取在<input type='file'>标签上传<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);
 }

使用event.target.files进行change事件以检索File实例。

$('#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/

此解决方案使用所有浏览器都不支持的File API - 请参阅http://caniuse.com/#feat=fileapi

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM