How to Preview Images Before Uploading
Jul 13 2024
Previewing images before uploading them to the server helps users confirm their selections. With the JavaScript FileReader API, this can be easily achieved. Let's see an example.
HTML Structure
In the first step, add an input element with the type attribute set to file and an accept attribute specifying that only image files can be selected by users. Then, add a container element where the image will be displayed.
<!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 FileReader API
In the second step, add an event listener to the input element, listening for the change event, which occurs when the user selects a file. When a file is selected, the event object e is passed to the event handler function. e.target.files is a FileList object containing the selected files. e.target.files[0] gets the first selected file.
If a file is selected, create a FileReader object to read the contents of the file. When the file has been read successfully, the onload event of the FileReader is triggered. Then, set the src attribute of the image element to the file's data URL. Finally, append the newly created image element to the container, displaying the image preview.
If no file is selected, simply 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
The last step, it is up to you. to make the preview look more appealing, use CSS to style the image and its container
#previewContainer {
margin-top: 10px;
}
#previewContainer img {
max-width: 100%;
max-height: 300px;
}
Conclusion
Previewing files before uploading them to a server with JavaScript FileReader API 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