Show an image preview before upload

前端 未结 5 962
天命终不由人
天命终不由人 2020-11-22 14:15

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

 

Then I\'m selecting multiple files b

相关标签:
5条回答
  • 2020-11-22 14:23

    Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).

    Don't forget to validate image extension.

    <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);
    
    
    0 讨论(0)
  • 2020-11-22 14:26

    For background images, make sure to use url()

    node.backgroundImage = 'url(' + e.target.result + ')';
    
    0 讨论(0)
  • 2020-11-22 14:27

    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>

    0 讨论(0)
  • 2020-11-22 14:28

    Here I did with jQuery using FileReader API.

    Html Markup:

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

    jQuery:

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

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

    0 讨论(0)
  • 2020-11-22 14:41

    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 FileReader interface which lets web applications asynchronously read the contents of files .

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

    The html code:

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

    The JavaScript code:

    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.

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

    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>

    0 讨论(0)
提交回复
热议问题