Html 上传前显示图像预览

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14069421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:36:22  来源:igfitidea点击:

Show an image preview before upload

htmlimage-processingupload

提问by Hardik Sondagar

In my HTML form I have input filed with type file for example :

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

 <input type="file" multiple>

Then I'm selecting multiple files by clicking that input button. Now I want to show preview of selected images before submitting form . How to do that in HTML 5?

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

回答by Kamyar Nazeri

HTML5 comes with File API spec, which allows you to create applications that let the user interact with files locally; That means you can load files and render them in the browser without actually having to upload the files. Part of the File API is the FileReaderinterface which lets web applications asynchronously read the contents of files .

HTML5 带有File API spec,它允许您创建让用户与本地文件交互的应用程序;这意味着您可以加载文件并在浏览器中呈现它们,而无需实际上传文件。File API 的一部分是FileReader接口,它允许 Web 应用程序异步读取文件的内容。

Here's a quick example that makes use of the FileReaderclass to read an image as DataURL and renders a thumbnail by setting the srcattribute of an image tag to a data URL:

这是一个快速示例,它使用FileReader该类将图像读取为 DataURL 并通过将src图像标记的属性设置为数据 URL 来呈现缩略图:

The html code:

html代码:

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

The JavaScript code:

JavaScript 代码:

document.getElementById("files").onchange = function () {
    var reader = new FileReader();

    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("image").src = e.target.result;
    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);
};

Here's a good article on using the File APIs in JavaScript.

这是一篇关于在 JavaScript 中使用文件 API的好文章。

The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:

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

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>

回答by Satinder singh

Here I did with jQuery using FileReader API.

在这里,我使用 FileReader API 使用 jQuery。

Html Markup:

Html 标记:

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

jQuery:

jQuery:

Here in jQuery code,first I check for file extension. i.e valid image fileto be processed, then will check whether the browser support FileReaderAPI is yes then only processed else display respected message

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

$("#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");
     }
 });

Detailed Article: How to Preview Image before upload it, jQuery, HTML5 FileReader() with Live Demo

详细文章:如何在上传前预览图像、jQuery、HTML5 FileReader() 和 Live Demo

回答by yogesh chatrola

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>

回答by epicgear

For background images, make sure to use url()

对于背景图片,请确保使用 url()

node.backgroundImage = 'url(' + e.target.result + ')';