π· File Upload with Image Preview
π This is how it looks π
π Live Demo
<form action="upload.php" method="post" enctype="multipart/form-data" onsubmit="event.preventDefault()">
<p>Please select an image:</p>
<input type="file" accept="image/*" onchange="previewImage(event)">
<div style="margin-top: 1em;">
<img id="imagePreview" src="#" alt="Preview image" style="display:none; max-width:100%;">
</div>
<button type="submit" style="margin-top: 1em;">π€ Submit</button>
</form>
<script>
function previewImage(event) {
const img = document.getElementById("imagePreview");
img.src = URL.createObjectURL(event.target.files[0]);
img.style.display = "block";
}
</script>
π Meaning and Usage of Form Attributes
β action="upload.php"
Specifies the destination URL where the form data will be sent upon submission.
<form action="upload.php" ...>
Note: You can create your own upload.php to save the image on your server, or use an external service URL (e.g., Amazon S3, Google Drive API, etc.).
β‘ enctype="multipart/form-data"
Required encoding type for uploading image or binary data.
<form enctype="multipart/form-data" ...>
If not specified: File data may not be transmitted correctly to the server.
β’ onsubmit="event.preventDefault()"
Prevents actual submission. Good for live previews.
<form onsubmit="event.preventDefault()" ...>
In production: Remove it or trigger form.submit() via JS manually.
π§ͺ Complete Example
<form action="upload.php" method="post" enctype="multipart/form-data" onsubmit="event.preventDefault()">
Uses & Benefits of This Template
- Instantly preview the selected image
- Provides an intuitive user experience
- Easy to add to any upload UI
- Useful for portfolios, product image uploads, etc.
- Simple enough for JS beginners to understand
π§© Applications and Use Cases
The image preview feature is a standard enhancement used in e-commerce sites and profile creation pages to improve user experience. By displaying the selected image immediately, it also helps prevent uploading mistakes.
This template uses URL.createObjectURL() to generate a temporary URL for the selected image file. This allows users to preview images instantly without uploading them to the server.
In addition, img.style.display = "block" is used to control the visibility, so the image is only shown after selection.
If you'd like to add restrictions such as file size or format validation, you can use properties like event.target.files[0].type or .size for customization.
Getting comfortable with this basic setup makes it easier to expand functionality later onβsuch as supporting multiple previews or drag-and-drop uploads.