13

I can read the uploaded image by using javascript fileReader but how can i read the uploaded image in jquery so that i can preview the image before uploading ?

Salim Qureshi
  • 131
  • 1
  • 1
  • 6

5 Answers5

41

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#previewHolder').attr('src', e.target.result);
    }
    reader.readAsDataURL(input.files[0]);
  } else {
    alert('select a file to see preview');
    $('#previewHolder').attr('src', '');
  }
}

$("#filePhoto").change(function() {
  readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<br/><br/>
<input type="file" name="filePhoto" value="" id="filePhoto" class="required borrowerImageFile" data-errormsg="PhotoUploadErrorMsg">
<br/><br/>
<img id="previewHolder" alt="Uploaded Image Preview Holder" width="250px" height="250px" style="border-radius:3px;border:5px solid red;"/>
Suresh Pattu
  • 5,399
  • 14
  • 50
  • 87
  • 2
    This worked for me but had to make a slight adjustment, I had to give an index to `input.files[0]` so `input[0].files[0]` – kabuto178 Jul 02 '15 at 11:29
8

using javascript

<div class="form-group">   
    <label for="password" class="form-group">upload Image</label>
    <input id="image" type="file" name="image" onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])" required="required">
    <img id="blah"  width="50" height="50" />
</div>
Merrin K
  • 792
  • 1
  • 7
  • 17
  • Can you add some explanation to your code? Why do you think that it solves the problem? Which parts where neccessary? Please do not only post code, this makes it nearly impossible for the OP to spot his error – Nico Haase Dec 14 '18 at 12:20
  • Best one ❤️ , Thanks – Golam Sorwar May 18 '19 at 19:23
  • @NicoHaase the question had no question, afterall was only a question on how to do it. This answer altought doesnt have explications, is the simplest working one. – David Alves Mar 12 '20 at 14:57
2

To Preview the image before Uploading using jquery

Create an event onchange which will be triggered when selecting any image, function loadImg() can be used to load the image within the frame.

Live example:

function loadImg(){
    $('#frame').attr('src', URL.createObjectURL(event.target.files[0]));
}
<html>
<head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <input type="file" accept="image/" onchange="loadImg()"><br/>
    <img id="frame"  width="100px" height="100px"/>
</body>
</html>
Merrin K
  • 792
  • 1
  • 7
  • 17
1

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script src="jquery-3.1.1.min.js"></script>
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
  
<style type="text/css">
p1{
    color:orange;
}
p2{
    color:green;
}

 .thumb-image
 {
    float:left;
    width:50px;
    position:relative;
    padding:2px;
}

body{
                
                }
        
            #form label{
                font:bold 11px arial;
                color: #565656;
                padding-left: 1px;
            }
            #form label.mandat{color:red;}
            
           
            #form img{
                margin-bottom: 8px;
            }
            #form input[type="submit"]{
                background-color: #0064aa;
                border: none;
                color: #fff;
                padding: 5px 8px;
                cursor: pointer;
                font:bold 12px arial;
            }
            .error{
                border: 1px solid olive;
            }
            


</style>
  
  <script>
$.validator.addMethod("error9", function(value, element, error) {          
    return error.test(value);
} );




  $(function() {
  
  
    $("#register-form").validate({
    
       
        rules: {
           
               
        pic: {
            required: true,
            error9: /(?=.(gif|png|jpg|jpeg))/

        }
        
        

        },

        messages: {


          
            pic: {
            required: "<p1>Please upload image</p1>",
            error9: "<p2> only accept jpg,gif,png</p2>"
        }

           
        },
        
        submitHandler: function(form) {
            form.submit();
        }
    });

  });
  
  </script>
  <script>
$(document).ready(function() {
        $("#pic").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 {
              echo (image_holder);
            }
          } else {
            //alert ("Pls select only images");
          }
        });
      });
</script>


</head>
<body>

 <div style='margin:0 auto'>

<form name= "" id="register-form" action="loginformjq.php"  method="post">
<div id="form">
<table  border="1" padding="2" cellpadding="2" width="20%" bgcolor="lightblue" align="center" cellspacing="2">

<tr>
<td colspan=2>
<center><font size=4><p style="color: purple"><marquee direction="left" behavior="alternate" style="border:solid olive">Student Registration Form</marquee></p></font></center>
</td>
</tr>
               
                    
<tr><p style="color: yellow"><td>
<p class="error">
     <input type="file" name="pic"  id="pic"></p><span id="image-holder"> </span>
     </p></td></tr>



<tr>
<p style="color: yellow"></p>
<td colspan="1"><input type="submit" value="submit"></td>

</tr>
</table>
</form>
  
</div>
        
        
        </div>
</body>
</html>
0

Alternatively You can use jquery plugin also.

One good option is dropify.

Read More about Dropify

Rajen Trivedi
  • 709
  • 1
  • 2
  • 8