1

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

Kawazoe Kazuke
  • 175
  • 4
  • 19

3 Answers3

0

use FileReader, see How to show local picture in web page?

if no support, you can upload to server tmp dir first, then preview

$('#tmp_img').attr('src','tmp/tmp_hashnumber.jpg');

move it after make sure

Community
  • 1
  • 1
Vin
  • 101
  • 4
0

I think you are looking something like this. This is part of my previous solution. Here you will find a more complex implementation

//Console logging (html)
if (!window.console)
  console = {};

var console_out = document.getElementById('console_out');

console.log = function(message) {
  console_out.innerHTML += message + '<br />';
  console_out.scrollTop = console_out.scrollHeight;
}

function previewFile() { 
  var preview = document.getElementById('source_image');
  var file   = document.querySelector('input[type=file]').files[0]; 
  var reader  = new FileReader();
  reader.addEventListener("load", function(e) {
    preview.src = e.target.result; 
    preview.onload = function() {
      console.log('Image Loaded');
    };
  }, false);

  if (file) {  
    reader.readAsDataURL(file);
  }
}
<input type="file" onchange="previewFile()"><br>
<div>
  <h3>Original Image before Upload</h3>
  <img id="source_image" alt="Image preview..." />
</div>

<div>
  <fieldset>
    <legend>Console output</legend>
    <div id='console_out'></div>
  </fieldset>
</div>
Community
  • 1
  • 1
Teocci
  • 4,348
  • 1
  • 34
  • 36
0

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>
guest271314
  • 1
  • 10
  • 82
  • 156
  • How can i size the image preview size? I mean when the image is 1024x1024 then the imgae preview show as it's size but i want to show preview as i limited preview size. For example : the image preview size should be 512x512. – Kawazoe Kazuke May 02 '17 at 03:52
  • Resize image to `.height` `"512px"`, `.width` `"512px"` only when image dimensions are or exceed `.width` `"1024px"`? – guest271314 May 02 '17 at 04:04
  • Can I show image with Bootstrap Modal? How can i do that? – Kawazoe Kazuke May 02 '17 at 05:20
  • How is Bootstrap Modal related to original Question _"How to show image preview before Upload?"_? See https://stackoverflow.com/help/how-to-ask – guest271314 May 02 '17 at 05:23
  • Yeah, I know. But I do as your code and show my boss, then he want to show preview image with bootstrap modal. That's why i need help from you. :( – Kawazoe Kazuke May 02 '17 at 05:24
  • _"Yeah, I know. But I do as your code and show my boss, then he want to show preview image with bootstrap modal. That's why i need help from you. :("_ Then do your job. That has nothing to do with original Question either. – guest271314 May 02 '17 at 05:26
  • 1
    Ok.. Anyway Thanks for helping me out this range buddy. ;) – Kawazoe Kazuke May 02 '17 at 05:30