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