jQuery抓取一个用input type ='file'上传的文件 [英] jQuery grab a file uploaded with input type='file'

查看:254
本文介绍了jQuery抓取一个用input type ='file'上传的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to grab the file uploaded in a <input type='file'> tag.

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

When I do $('#inputId').val(), it only grabs the name of the file, not the actual file itself.

我正在尝试这样做:

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 for 更改事件以检索文件实例。

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

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

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

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

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

这篇关于jQuery抓取一个用input type ='file'上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆