WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
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, website design and basically anything digital-related. His main expertise is with WordPress and various other CMS frameworks. If you need responsive design, SEO, speed optimisation or anything else in the world of digital, you can contact Silva Web Designs here; [email protected]

It’s good to share

Join the discussion

Related Posts

Related - CSS – Indenting the second line of LI (List Items)

CSS / 25th September 2023

CSS – Indenting the second line of LI (List Items)

Read More Related - How To Add Line On Either Side Of Your Text Headers With CSS

CSS / 23rd September 2023

How To Add Line On Either Side Of Your Text Headers With CSS

Read More