Now, we’re going to show you how to show a preview image of a file that you upload using the HTML input type file. Let’s image you have the following HTML markup:
<img id="preview" 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;
}
Here, 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) {
$('#preview')
.attr('src', e.target.result);
$('#preview').show();
};
reader.readAsDataURL(input.files[0]);
}
}
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.
Total Views: 85