Steven Spielberg
Steven Spielberg

Reputation:

Showing a preview of the image file that user wants to upload on the website

How i can show a preview of the image which the user chooses to upload on website.

I mean, when a user chooses the file from their system, have the web-page already show them the files they want to upload. how I can do this using HTML and jQuery?

Upvotes: 0

Views: 3710

Answers (2)

Ajey
Ajey

Reputation: 8202

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



$(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);
  });
});

you can use this fiddle http://jsfiddle.net/Kulgar/57F67/

Upvotes: 0

Konerak
Konerak

Reputation: 39763

You can't, atleast not in all browsers.

This is because some browsers provide the entire path to the <input type='file'> - this way you can try and show the element on the users harddisk (do watch out for certain browsers' security settings)

Other browsers just provide a filename - you've got nothing to show here.

What you can always do, is upload the file using jQuery (.ajax, so the page does not get refreshed) and then show it to the user already. In these modern times, uploading a file is not that disturbing (especially if you provide an animation while it's working).

If you really need this feature, you can always use a Java Applet (think facebook or imageshack) to allow for previews. Not every user has (a recent enough version of) Java installed and enabled though.

If you still want to implement this for browsers that do provide the full path (say, you work in a corporate environment and everyone uses the same browser, or you have it degrade gracefully and just offer the feature to the users for whom it works), you just use the .val() of the <input type='file'> to get the path to the filename. Add a file:// before and display (dump in an img or so)

More info:

Upvotes: 1

Related Questions