Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preview image before uploading in jquery

Tags:

jquery

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 ?

like image 244
Salim Qureshi Avatar asked Sep 09 '13 08:09

Salim Qureshi


3 Answers

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;"/>
like image 200
Suresh Pattu Avatar answered Nov 18 '22 12:11

Suresh Pattu


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>
like image 23
vijay pancholi Avatar answered Nov 18 '22 13:11

vijay pancholi


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>
like image 4
Merrin K Avatar answered Nov 18 '22 12:11

Merrin K