Preview an image before it is uploaded

P

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:

[code]
<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>
[/code]

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:

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

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

About the author

By Jamie

My Books