Click here to Skip to main content
15,891,657 members
Articles / Web Development / HTML5
Tip/Trick

Display the Preview of an Image Before Uploading It To Server

Rate me:
Please Sign up or sign in to vote.
4.44/5 (5 votes)
31 Aug 2015CPOL3 min read 18.6K   110   6   18
Display the uploaded image in the DOM before sending it to the server.

If you want, you can also fork the project on Github.

Introduction

Many times, I have come across the issue of displaying a preview of the uploaded image to the user. And for that, we need assign the image URL to the src attribute of the img tag in the HTML. To get a URL, we have to upload the image to the server and assign the path to the attribute. But in this tip, I will show you how to create a URL from the client's machine and assign it to the src attribute.

Setting Up the HTML

Basically, what we need here is that, we need an upload button through which the user can select a local file from his/her machine. And a submit button to submit the image to the server. But that is not important for our description. We want to show the user a preview of the image he has submitted, before it is sent to the server.

HTML
<img id="previewImage" src="http://placehold.it/550x270&text=No+Attachment!" 
	alt="" height="270px" width="550"/>
   <form role="form">
          
<label for="uploadImage">Select File</label>
          <input id="uploadImage" type="file">
          <button id="submitButton" 
type="submit" >Submit</button>
   </form>

The above HTML set a placeholder for the image and an upload button. There is a submit button to send the form to the server. But for the time being, we do not need it. Two tags are important for us. One is the img tag and the other is the input tag with type file.

HTML
<img id="previewImage" src="http://placehold.it/550x270&text=No+Attachment!" 
	alt="" height="270px" width="550"/>

Let's say this is the placeholder for the image. In the beginning, its source has been assigned to a value of http://placehold.it/550x270&text=No+Attachment!. This URL generates images with text dynamically depending upon the URL. For example, this URL will generate an image of size 550*270 with the text No Attachment!

HTML
<input id="uploadImage" type="file">

The other important tag in the HTML is the input tag with the type file. This is the upload button.

Setting Up the JavaScript

Now let's have a look at the JavaScript used for this purpose. I have used the JQuery library for the DOM and event manipulation as it makes life easier. You can do the same thing using the raw JavaScript.

JavaScript
//Call the function each time the user changes a function
        $('#uploadImage').change(function () {
            //Check if a file has been selected or not
            if (this.files && this.files[0]) {
                //Check if the uploaded file is an Image file
                if (this.files[0].type.startsWith('image/')) {
                    var reader = new FileReader();
                    reader.readAsDataURL(this.files[0]);
                    reader.onloadend = function () {
                                        $('#previewImage').attr('src', reader.result);
                                        }     
                } else {
                    //If an image is not selected then show an other image. 
                    $('#previewImage').attr
                    ('src', 'http://placehold.it/550x270&text=No+PreView!');                    
                }
            }
        });

The above code is self explanatory. Each time the user changes a file, we are calling a function that is checking if a file has been selected or not. If a file is selected, then it's reading the type of the file. And if the type is image/*, it's updating the src of the img tag. The trick here is the following lines.

JavaScript
var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
reader.onloadend = function () {
    $('#previewImage').attr('src', reader.result);
    }

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the <a href="https://developer.mozilla.org/en-US/docs/Web/Events/loadend" title="/en-US/docs/Web/Events/loadend">loadend</a> is triggered. At that time, the result attribute contains the data as a URL representing the file's data as a base64 encoded string. And in the <a href="https://developer.mozilla.org/en-US/docs/Web/Events/loadend" title="/en-US/docs/Web/Events/loadend">loadend</a> this data is assigned to the src of the img tag.

Please have a look at the screenshot from the Chrome developer tool. This base 64 encoded string is responsible for rendering the image in the DOM.

Image 1

If you want to read more about the FileReader in JavaScript, you can visit this website. This contains other properties and methods that can be helpful for you. This also contains some complex example, don't forget to have a look at them.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Mindfire Solutions
India India
Geek | A fullstack Developer | Big fan of Microsoft Technologies and AngularJS | A Gadgets Lover | I love technology and believe that someday others will love it too.

Comments and Discussions

 
QuestionNeed help for few line code Pin
Tridip Bhattacharjee8-Sep-15 21:24
professionalTridip Bhattacharjee8-Sep-15 21:24 
AnswerRe: Need help for few line code Pin
Swagat Swain8-Sep-15 22:00
professionalSwagat Swain8-Sep-15 22:00 
GeneralIE support!! Pin
Prava-MFS31-Aug-15 23:07
professionalPrava-MFS31-Aug-15 23:07 
GeneralRe: IE support!! Pin
Swagat Swain1-Sep-15 0:07
professionalSwagat Swain1-Sep-15 0:07 
GeneralRe: IE support!! Pin
Prava-MFS1-Sep-15 0:12
professionalPrava-MFS1-Sep-15 0:12 
GeneralRe: IE support!! Pin
Swagat Swain1-Sep-15 0:38
professionalSwagat Swain1-Sep-15 0:38 
GeneralRe: IE support!! Pin
Prava-MFS1-Sep-15 0:42
professionalPrava-MFS1-Sep-15 0:42 
GeneralRe: IE support!! Pin
Swagat Swain1-Sep-15 1:50
professionalSwagat Swain1-Sep-15 1:50 
QuestionMissing figure Pin
Amarnath S31-Aug-15 20:35
professionalAmarnath S31-Aug-15 20:35 
AnswerRe: Missing figure Pin
Swagat Swain31-Aug-15 20:37
professionalSwagat Swain31-Aug-15 20:37 
GeneralRe: Missing figure Pin
Amarnath S31-Aug-15 21:18
professionalAmarnath S31-Aug-15 21:18 
GeneralRe: Missing figure Pin
Swagat Swain31-Aug-15 21:24
professionalSwagat Swain31-Aug-15 21:24 
GeneralRe: Missing figure Pin
Amarnath S31-Aug-15 21:28
professionalAmarnath S31-Aug-15 21:28 
GeneralRe: Missing figure Pin
Swagat Swain31-Aug-15 22:08
professionalSwagat Swain31-Aug-15 22:08 
GeneralRe: Missing figure Pin
Amarnath S31-Aug-15 22:20
professionalAmarnath S31-Aug-15 22:20 
GeneralRe: Missing figure Pin
Swagat Swain1-Sep-15 5:32
professionalSwagat Swain1-Sep-15 5:32 
GeneralRe: Missing figure Pin
Amarnath S1-Sep-15 6:19
professionalAmarnath S1-Sep-15 6:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.