Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

Display the Preview of an Image Before Uploading It To Server

4.44/5 (5 votes)
31 Aug 2015CPOL3 min read 19.5K   110  
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)