Kannan Chakkara
Kannan Chakkara

Reputation: 201

Upload And Remove image

I have a upload button on my web page, if i upload an image it should show preview below and i upload another image it should show next to the image and for third it should show next to the second image and so on, and once i click the click the "X" the image should be removed. Here is my code

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Image preview</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">    
</script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"> 
</script>
<script>
var blank="http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif";
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#img_prev')
            .attr('src', e.target.result)
            .height(200);
        };

        reader.readAsDataURL(input.files[0]);
    }
    else {
      var img = input.value;
        $('#img_prev').attr('src',img).height(200);
    }
    $("#x").show().css("margin-right","10px");
}
$(document).ready(function() {
  $("#x").click(function() {
    $("#img_prev").attr("src",blank);
    $("#x").hide();  
  });
 });
 </script>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript">//<![CDATA[ 
$(window).load(function(){
$("input:file").change(function () {
       if ($(this).val() !== "") {
        var file = $('#file_select')[0].files[0];
        console.log(file.size);
        //console.log(file.width);
        var reader = new FileReader();
         var img = new Image();
        var _URL = window.URL || window.webkitURL;
        reader.readAsDataURL(file);
        reader.onload = function(_file) {
            img.src= _file.target.result;
            //$('#img_preview').append('<img src="'+ img.src +'"/>');
            $('#previewPane').append('<img id="img_prev" src="'+ img.src +'"   
alt="your image" /><span id="x">[X]</span>');
            //console.log(img.src);
            console.log(img.width);
         } 
       }
});
});//]]>  

</script>
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
#x { display:none; position:relative; z-index:200; float:right}
#previewPane { display: inline-block; }
</style>
</head>
<body>
<section>
<input type='file' name="file" id="file_select" onchange="readURL(this);" />   
<br/>
<span id="previewPane">
</span>
</section>
</body>
</html>

Upvotes: 1

Views: 3547

Answers (2)

Vikash
Vikash

Reputation: 1139

It's simple :

 

   
 $(function(){
    $('input[type=file]').change(previewFile);
   
    
 function previewFile() {
     var el=$('#preview');
  var preview = $(document.createElement('img'))[0];
     preview.height=200;
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    preview.src = reader.result;
  }

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
     var imgdiv=$(document.createElement('div')).append(preview).append('<span>x</span>');
      $(imgdiv).find('span').click(function(){
       $(this).parent().remove();
    });
     el.append(imgdiv);
}

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" ><br>
<div id="preview"></div>

Reference : https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

Upvotes: 0

fuyushimoya
fuyushimoya

Reputation: 9813

  1. Remove readURL and onchange="readURL(this);" on input which is doing samething(I beleive) with $("input:file").change.

  2. Create a div.imageContainer to Wrap both img and span, so when X on the span is clicked, it knows which image to be removed.

  3. Add a delegated click event listener to $('#previewPane') and told it to react to every click that is sourced from .remover, which is an added class on the span, so we don't need to register each click event when a new image is coming.

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Image preview</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">    
</script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"> 
</script>
<script>
    var blank="http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif";
</script>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript">//<![CDATA[ 
$(window).load(function(){
    $('input[type="file"]').change(function () {
       if ($(this).val() !== "") {
        var file = $('#file_select')[0].files[0];
        console.log(file.size);
        //console.log(file.width);
        var reader = new FileReader();
        var img = new Image();
        var _URL = window.URL || window.webkitURL;
        reader.readAsDataURL(file);
        reader.onload = function(_file) {
            // Create a container for image and span X
            $imageItem = $('<div>').addClass('imageItem');
            $(img).appendTo($imageItem);
            $('<span>').html('x').addClass('remover').appendTo($imageItem);
            img.src= _file.target.result;

            // Append the container to panel
            $('#previewPane').append($imageItem);
            //console.log(img.src);
            console.log(img.width);
        } 
    }

    // Deletegate for dynamically created span, so we don't have to register a
    // new event listener each time a new imageContainer is created.
    $('#previewPane').on('click', '.remover', function() {
        $this = $(this);
        $this.parent('.imageItem').remove();
    });
});
});//]]>

</script>
<style>
article, aside, figure, footer, header, hgroup,
    menu, nav, section { display: block; }
    #x { display:none; position:relative; z-index:200; float:right}
    #previewPane { display: inline-block; }
</style>
</head>
<body>
<section>
<input type='file' name="file" id="file_select"/>   
<br/>
<span id="previewPane">
</span>
</section>
</body>
</html>

Upvotes: 1

Related Questions