Follow @endyourif rss Facebook LinkedIn

Preview an image before it is uploaded Preview an image before it is uploaded

Published on Jun 19, 2022

This is something I haven't really thought of before, typically when I implement a file upload for an image the preview happens after. However, there is actually a really simple way to get a preview of it before the actual upload happens to the server. Let's take a look at an example.



To start with, you need a basic form with a file input and an element that will preview the image:


<form method="POST" action="myServerSideCode.php">
<label for="image">Upload image:</label>
<input id="image" type="file" oninput="pic.src=window.URL.createObjectURL(this.files[0])">

<img id="pic" />
</form>


The following solution leverages the oninput function to set the src of the img tag with the id of pic.

This can also be accomplished with a JavaScript array event for the onchange type:


image.onchange = evt => {
const [file] = image.files
if (file) {
pic.src = URL.createObjectURL(file)
}
}


Both methods work basically the same way as they rely on the URL.createObjectURL function.

Tags: JavaScript | image | file

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP