124

在我的 HTML 表单中,我输入了类型文件,例如:

 <input type="file" multiple>

然后我通过单击该输入按钮来选择多个文件。现在我想在提交表单之前显示所选图像的预览。如何在 HTML 5 中做到这一点?

4

5 回答 5

274

下面是一个快速示例,它通过将图像标签的属性设置为对象 URL 来使用URL.createObjectURL来呈现缩略图:src

html代码:

<input accept="image/*" type="file" id="files" />
<img id="image" />

JavaScript 代码:

document.getElementById('files').onchange = function () {
  var src = URL.createObjectURL(this.files[0])
  document.getElementById('image').src = src
}

下面 HTML 示例中的代码片段从用户选择中过滤掉图像,并将所选文件呈现为多个缩略图预览:

function handleFileSelect (evt) {
  // Loop through the FileList and render image files as thumbnails.
  for (const file of evt.target.files) {
 
    // Render thumbnail.
    const span = document.createElement('span')
    const src = URL.createObjectURL(file)
    span.innerHTML = 
      `<img style="height: 75px; border: 1px solid #000; margin: 5px"` + 
      `src="${src}" title="${escape(file.name)}">`

    document.getElementById('list').insertBefore(span, null)
  }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" accept="image/*" id="files" multiple />
<output id="list"></output>

于 2012-12-28T12:20:45.623 回答
22

在这里,我使用 FileReader API 处理了 jQuery。

html标记:

<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>

jQuery:

在 jQuery 代码中,首先我检查文件扩展名。即要处理的有效图像文件,然后将检查浏览器是否支持FileReader API 是然后只处理否则显示尊重的消息

$("#fileUpload").on('change', function () {
 
     //Get count of selected files
     var countFiles = $(this)[0].files.length;
 
     var imgPath = $(this)[0].value;
     var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
     var image_holder = $("#image-holder");
     image_holder.empty();
 
     if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
         if (typeof (FileReader) != "undefined") {
 
             //loop for each file selected for uploaded.
             for (var i = 0; i < countFiles; i++) {
 
                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $("<img />", {
                         "src": e.target.result,
                             "class": "thumb-image"
                     }).appendTo(image_holder);
                 }
 
                 image_holder.show();
                 reader.readAsDataURL($(this)[0].files[i]);
             }
 
         } else {
             alert("This browser does not support FileReader.");
         }
     } else {
         alert("Pls select only images");
     }
 });
于 2015-07-27T15:56:29.897 回答
4

function handleFileSelect(evt) {
    var files = evt.target.files;

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = 
          [
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', 
            e.target.result,
            '" title="', escape(theFile.name), 
            '"/>'
          ].join('');
          
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" multiple />
<output id="list"></output>

于 2016-08-30T09:19:14.397 回答
2

对于背景图像,请务必使用url()

node.backgroundImage = 'url(' + e.target.result + ')';
于 2019-02-19T02:44:25.513 回答
2

如果没有FileReader,我们可以使用URL.createObjectURL方法来获取表示对象(我们的图像文件)的 DOMString。

不要忘记验证图像扩展名。

<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');

const handle_file_preview = (e) => {
  let files = e.target.files;
  let length = files.length;

  for(let i = 0; i < length; i++) {
      let image = document.createElement('img');
      // use the DOMstring for source
      image.src = window.URL.createObjectURL(files[i]);
      image_preview.appendChild(image);
  }
}

file_input.addEventListener('change', handle_file_preview);

于 2020-09-19T16:56:47.080 回答