I’m looking for a simple javascript upload image
solution where the user selects an image, and it’s instantly displayed on the page using multiple <img src>
elements (to show different sizes). Here’s what I have so far using jQuery and FileReader
, but I want to ensure it’s the right approach or if there’s a better way.
I’ve worked with front-end tools for over a decade, and honestly, for a clean solution, this is my go-to for javascript upload image:
Pure JavaScript with FileReader (Simple & Reliable) :
<input type="file" id="imageUpload" accept="image/*" />
<img id="preview" width="150" />
<img id="thumbnail" width="50" />
<script>
document.getElementById('imageUpload').addEventListener('change', function (event) {
const file = event.target.files[0];
if (file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = function (e) {
document.getElementById('preview').src = e.target.result;
document.getElementById('thumbnail').src = e.target.result;
};
reader.readAsDataURL(file);
}
});
</script>
Why I like this: I used this exact approach in a profile photo uploader—it’s fast, no libraries, and works everywhere.
Totally agreeing with @ishrth_fathima, if @sakshikuchroo you are already using jQuery, then I think the below code should help you.
<input type="file" id="imageUpload" />
<img id="preview" width="150" />
<img id="thumbnail" width="50" />
<script>
$('#imageUpload').on('change', function () {
const file = this.files[0];
if (file && file.type.match('image.*')) {
const reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
$('#thumbnail').attr('src', e.target.result);
};
reader.readAsDataURL(file);
}
});
</script>
Why I used this: On older jQuery-based projects, this made it super easy to drop into existing code with minimal effort.
Thanks for the solutions @ishrth_fathima and @netra.agarwal
But i built this drag-and-drop image upload feature for a design tool I was working on.
The goal was to let users quickly drop in images without clicking through file dialogs, it makes the whole interface feel cleaner, smoother, and way more modern.
Just dropping an image in and seeing a live preview instantly gives it that polished UX touch.
<div id="dropZone" style="border: 2px dashed #ccc; padding: 20px;">Drop image here</div>
<img id="preview" width="150" />
<script>
const dropZone = document.getElementById('dropZone');
dropZone.addEventListener('dragover', (e) => e.preventDefault());
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
const file = e.dataTransfer.files[0];
if (file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (e) => {
document.getElementById('preview').src = e.target.result;
};
reader.readAsDataURL(file);
}
});
</script>
When I used this: I built this for a design tool where users could drop in images directly, makes the interface feel way smoother and modern.