문제

I am allowing the user to see the uploaded image preview before it is saved to the database. The HTML code is :

<div class="upload-preview">
  <img />
</div>
<input class="file" name="logo" type="file">

And my jquery code is :

$(document).ready(function(){
var preview = $(".upload-preview img");

$(".file").change(function(event){
   var input = $(event.currentTarget);
   var file = input[0].files[0];
   var reader = new FileReader();
   reader.onload = function(e){
       image_base64 = e.target.result;
       preview.attr("src", image_base64);
   };
   reader.readAsDataURL(file);
  });
});

The above code works great for one image. What if I want to upload 10 images, I have to repeat the code 10 times.

I tried to generalize it but since the jquery code depends on the html class the image is uploaded to all the matching classes.

If I use an ID then I would have to repeat the jquery code for each ID.

Is there any way to generalize this problem so that it can preview multiple images with just one jquery function.

도움이 되었습니까?

해결책

Change you HTML code by this:

<div class="upload-preview" id="upload-preview">

</div>
<input class="file" name="logo" type="file"/>

And JS code by this one:

$(document).ready(function(){
var preview = $("#upload-preview");

$(".file").change(function(event){
   var input = $(event.currentTarget);
   var file = input[0].files[0];
   var reader = new FileReader();
   reader.onload = function(e){
       image_base64 = e.target.result;
       preview.append("<img src='"+image_base64+"'/><br/>");
   };
   reader.readAsDataURL(file);
  });
});
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top