jQuery захватывает загруженный файл с вводом type = 'file' - PullRequest
14 голосов
/ 08 января 2012

Я хочу получить файл, загруженный в тег <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 голосов
/ 08 января 2012

Используйте event.target.files для события change для извлечения экземпляров файла.

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

3 голосов
/ 08 января 2012

Вероятно, это относится к свойству HTML5 files. См w3 и образец jsfiddle

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...