显示从文件选择器中选择的图像的图像缩略图

Display image thumbnail of image selected from filepicker

本文关键字:图像 略图 选择 文件 选择器 显示      更新时间:2023-11-20

我使用一个常规的HTML文件选择器输入表单项来允许我的用户选择文件。我想给他们看一个他们选择的文件的缩略图,因为他们需要选择很多图像,这可能会让人困惑。

是否有人知道是否可以在不上传到服务器的情况下显示他们选择的图像?如果是,如何?

如果有人能给我指一个帖子,或者给我一个如何做到这一点的想法,我将不胜感激。

<input type="file" name="image" accept="image/*">

<!-- Create an <img> element to preview the image -->
<img id="image-preview" width="320">
<!-- The <input> can go anywhere in your page or <form>. Note the "onchange" attribute -->
<input type="file" name="image" accept="image/*" onchange="handleFileChange">

请确保以下JavaScript位于上述<img><input>元素之后。您可以将其放入页面末尾加载的.js文件中,也可以放入页面末尾的<script>元素中。

// Select the preview image element
const imgElement = document.getElementById('image-preview');
function handleFileChange(e) {
    // If no file was selected, empty the preview <img>
    if(!e.target.files.length) return imgElement.src = '';
    // Set the <img>'s src to a reference URL to the selected file
    return imgElement.src = URL.createObjectURL(e.target.files.item(0))
}

这应该会让你开始

http://jsfiddle.net/41go76g4/

基本上,您使用javascript中的fileAPI读取文件,并将返回的blob设置为img标记的dataURL。

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    // 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 class="thumb" 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('fileInput').addEventListener('change', handleFileSelect, false);

参考:http://www.html5rocks.com/en/tutorials/file/dndfiles/