Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMSSQLMySQLPHPSilvaTechnologiesWordpress
Silva Web Designs - Blog

How to show a preview image of an input file upload

Today we’re going to show you how to show a preview image of a file that you upload using the HTML input type file.

Okay, let’s dig right into it, firstly, let’s image you have the following HTML markup:-


<input type="file" onchange="readURL(this);" />
<img id="blah" alt="Your Image Preview" />

We’re going to add a bit of CSS styling to hide the image initially and only display the image once the file has been uploaded.


img {
  max-width: 180px;
  display: none;
}

input[type=file] {
  padding: 10px;
  background: #2d2d2d;
  color: #FFF;
  display: block;
  margin-bottom: 20px;
}

Now, we just need the jQuery function to show the preview and add the uploaded file to replace the image, you can do this as follows:


function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#blah')
        .attr('src', e.target.result);
      $('#blah').show();
    };

    reader.readAsDataURL(input.files[0]);
  }
}

The end result will look something as follows:-

If you take a look at this blog post, you will see how you can take this one step further to make it even more visually appealing 😉

This is a pretty cool feature to add to file uploads to make them a bit more visually impressive to the user.

You can check out and test the CodePen we created here.

As always, we hope you have found this useful… make sure to leave a comment and stay tuned for the next tutorial!

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development and web site design. His expertise is WordPress & Magento as well as many other frameworks. Would you like to work with Nathan? Send him an email on [email protected]

It’s good to share

Join the discussion