Learn how to implement an image preview feature before upload using HTML, JavaScript, and Tailwind CSS. Includes drag-and-drop functionality, multiple file selection, and responsive design.
Article Body
How to Create Image Preview Before Upload - HTML, JavaScript & Tailwind CSS Tutorial
In this tutorial, we'll build a modern image upload interface that shows previews of selected images before uploading. The solution includes drag-and-drop functionality, multiple file selection, and a clean UI built with Tailwind CSS.
function updateUploadInfo() {
if (selectedFiles.length > 0) {
uploadInfo.classList.remove('hidden');
selectedCount.textContent = selectedFiles.length;
uploadBtn.disabled = false;
// Calculate total size
const totalSize = selectedFiles.reduce((total, file) => total + file.size, 0);
const sizeInMB = (totalSize / (1024 * 1024)).toFixed(2);
// Update info text
uploadInfo.querySelector('span').innerHTML = `
${selectedFiles.length} image(s) selected (${sizeInMB} MB) ready for upload
`;
} else {
uploadInfo.classList.add('hidden');
uploadBtn.disabled = true;
}
}
Step 8: Implement the Upload Button
uploadBtn.addEventListener('click', () => {
if (selectedFiles.length) {
// In a real application, you would upload the files here
alert(`Preparing to upload ${selectedFiles.length} image(s)`);
console.log('Files to upload:', selectedFiles);
// Simulate upload
setTimeout(() => {
alert('Upload completed! (This is a demo)');
resetUploader();
}, 1500);
}
});
Conclusion
You've now created a fully functional image preview before upload component with:
Drag and drop support
Multiple file selection
Image preview thumbnails
File information display
Responsive design with Tailwind CSS
This can be easily integrated into any web application. For production use, you would replace the simulated upload with actual server communication using Fetch API or Axios.