簡體   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