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

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.

Published on Jun 19, 2022

Tags: JavaScript

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.