Explain Codes LogoExplain Codes Logo

How to make a simple image upload using Javascript/HTML

javascript
file-upload
image-upload
async-upload
Anton ShumikhinbyAnton Shumikhin·Jan 20, 2025
TLDR

Here's a quick code snippet for a direct, no-frills image upload using HTML and JavaScript:

<input type="file" id="imageInput" onchange="uploadImage()"/>
function uploadImage() { let imageFile = document.getElementById('imageInput').files[0]; // Grabbing the file like a boss fetch('/upload', { method: 'POST', body: new FormData().append('image', imageFile) }) .then(res => res.json()) .then(console.log) .catch(console.error); // Don't forget to handle errors like a pro }

Make sure your server is all prepped to handle the POST request at /upload. This is as basic as it gets - using the power of <input type="file"> to select the image and fetch to post it asynchronously.

Forget FileReader, remember the basics

Handling files doesn't always have to involve the FileReader API. In fact, in our case, it's completely unnecessary. Life is already complex, why add more? All you need is a simple <input type="file"> with accept="image/*" to ensure you only deal with the good stuff...images.

Want to see your image immediately?

Life's too short to wait for an image to load. Here's how to immediately display an image:

<img id="preview" src="" alt="Image Preview" /> <input type="file" id="imageInput" accept="image/*" onchange="displayImage(this)"/>
function displayImage(inputElement) { const file = inputElement.files[0]; // 'this' might be a keyword, but it's also a very handy word const imageURL = URL.createObjectURL(file); // URL magic, baby! document.getElementById('preview').src = imageURL; // Voila! Your image inputElement.value = null; //Let's not hold on to the past // Now this is what you call cleaning up after yourself! document.getElementById('preview').onload = () => { URL.revokeObjectURL(imageURL); }; }

Instant joy of seeing your selected image using URL.createObjectURL and URL.revokeObjectURL. Bonus points as it's efficient with memory and no page refresh needed.

Security? Check!

Always validate your inputs, especially files. Implement simple sanity checks on file extensions. Expert tip: Use AJAX techniques with fetch or Axios library. Not only can you track upload progress, you can also handle errors. And yes, you can use alerts for notifying about upload issues because who doesn't love popups!

Multi-tasking like a boss

What if, like your laundry, you want to upload multiple files? Use FormData to append several files. Let's go asynchronous:

async function uploadMultipleImages(files) { const formData = new FormData(); for (let file of files) { formData.append('images[]', file); } try { const response = await fetch('/multi-upload', {method: 'POST', body: formData}); const result = await response.json(); console.log(result); } catch (error) { console.error('Oops! Upload failed:', error); //Grace through adversity } }

Extra stealth mode features

What if there's more than one masterpiece, and you need to upload them all at once? Look no further:

<input type="file" id="multipleInput" accept="image/*" multiple onchange="uploadMultiple(this.files)"/>

The multi-file upload handled like a pro. And oh, error handling's in there as well.