How to Preview Images Before Uploading
By onjsdev
Apr 7th, 2024
Previewing images before uploading them to the server help users confirm their selections. With the Javascript FileReader API, it can be easily achieved. Let's see an example.
HTML Structure
Here, we have an input element with the id fileInput
and accept
attribute that specifies that only image files are accepted to allow users to select a file.
<!DOCTYPE html>
<html>
<head>
<title>File Preview Example</title>
</head>
<body>
<input type="file" id="fileInput" accept="image/*">
<div id="previewContainer"></div>
<script src="script.js"></script>
</body>
</html>
JavaScript for Preview
In Javascript side, when a file is selected, we read the selected file using the FileReader API. We then create an image element and set its source to the data URL obtained from the FileReader API.
Finally, we update the preview container with the image. If no file is selected, we display a message indicating that no file is selected.
const fileInput = document.getElementById('fileInput');
const previewContainer = document.getElementById('previewContainer');
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (event) => {
const img = document.createElement('img');
img.src = event.target.result;
previewContainer.innerHTML = '';
previewContainer.appendChild(img);
};
reader.readAsDataURL(file);
} else {
previewContainer.innerHTML = 'No file selected';
}
});
Styling with CSS
To make the preview look more appealing, you can use CSS to style the image and container:
#previewContainer {
margin-top: 10px;
}
#previewContainer img {
max-width: 100%;
max-height: 300px;
}
Conclusion
Previewing files before uploading them to a server with JavaScript is a user-friendly feature that enhances the user experience. By following the steps outlined in this article, you can easily implement this functionality on your website.
Thank you for reading