Search code examples
javascriptjquerypreview

How to show image preview before Upload?


I want to show image preview before uploading process. In my case I selected multiple images with input file and the list of file name will show as link. When I click on the image file name link then the preview image popup will show of it's specific image. Here is my code..

<input id="uploadBtn" type="file" class="upload" multiple="multiple" name="browsefile" style="display: none !important;"/>

<input type="button" value="ファイル追加" onclick="document.getElementById('uploadBtn').click();" style="float: right;"/>

<input id="filename" type="hidden" />
<br>
<div id="upload_prev"></div>
<div style="clear:both;"></div>

Here is my javascript

<script type="text/javascript">
  $(document).on('click','.close',function(){
    $(this).parents('span').remove();
  })

  document.getElementById("uploadBtn").onchange = function () {
     document.getElementById("uploadFile").value = this.value;
  };

  document.getElementById('uploadBtn').onchange = uploadOnChange;

  function uploadOnChange() {
    var filename = this.value;
    var lastIndex = filename.lastIndexOf("\\");
    if (lastIndex >= 0) {
    filename = filename.substring(lastIndex + 1);
  }
var files = $('#uploadBtn')[0].files;
for (var i = 0; i < files.length; i++) {
  $("#upload_prev").append('<span><br><div class="col-md-10"><span class="uploadFiles">'+ '<a href="">' +files[i].name+ '</a>' +'</span></div><div class="col-md-2"><p class="close" style="font-size: 13pt;">削除</p><br></div></span>');
}
document.getElementById('filename').value = filename;
}
</script>

Here is Screenshot


Solution

  • You can use URL.createObjectURL() to create a Blob URL of uploaded image.

    Adjusted html to <div> as appended parent element instead of <span> element.

    At first click at <a> element, if next <div> does not contain <img> append <img> else call .toggle() to display <img>.

    At click at .close element, call .toggle() instead of .remove().

    You can also include an element, for example, <button>, which when clicked, creates a FormData instance to set all or selected File objects as entries of multipart/form-data to upload to server.

    $(document).on('click', '.close', function() {
      $(this).siblings("img").toggle();
    })
    
    document.getElementById("uploadBtn").onchange = function() {
      document.getElementById("uploadFile").value = this.value;
    };
    
    document.getElementById('uploadBtn').onchange = uploadOnChange;
    
    function uploadOnChange() {
      var filename = this.value;
      var lastIndex = filename.lastIndexOf("\\");
      if (lastIndex >= 0) {
        filename = filename.substring(lastIndex + 1);
      }
      var files = $('#uploadBtn')[0].files;
      for (var i = 0; i < files.length; i++) {
        (function(i) {
          $("#upload_prev").append('<div><br><div class="col-md-10"><span class="uploadFiles">' + '<a href="">' + files[i].name + '</a>' + '</span></div><div class="col-md-2"><p class="close" style="font-size: 13pt;">削除</p><br></div></div>');
          $("#upload_prev a:contains(" + files[i].name + ")")
            .on("click", function(e) {
              e.preventDefault();
              var close = $(this).closest("div")
                .next("div")
                .find(".close");
              if (!$(this).closest("div")
                .next("div").find("img").length) 
                close
                .after(
                  $("<img>", {
                    src: URL.createObjectURL(files[i])
                  })
                )
              else
                close.siblings("img").toggle()
            })
        })(i);
      }
    
      document.getElementById('filename').value = filename;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="uploadBtn" type="file" class="upload" multiple="multiple" accept="image/*" name="browsefile" style="display: none !important;" />
    
    <input type="button" value="ファイル追加" onclick="document.getElementById('uploadBtn').click();" style="float: right;" />
    
    <input id="filename" type="hidden" />
    <br>
    <div id="upload_prev"></div>
    <div style="clear:both;"></div>