
In this article, I am going to describe about how to preview multiple images before uploading using javascript.
If you want to preview only one image, the below article might be helpful.
[Javascript]How to preview an image before uploading
HTML
Put input element which type attribute is file and preview area.
By adding multiple attribute to input[type=file], user would be able to chose multiple files.
preview function (we will implement later) will be called when files are selected because of onchange attribute.
<input type="file" onchange="preview(this)" multiple>
<div class="preview-area"></div>
CSS
Let’s change the style for the preview area by CSS.
I made the images display in 4 columns here.
.preview-area{
display: flex;
flex-wrap: wrap;
}
.preview-area img{
width: 24%;
margin: 0 0 10px;
object-fit: contain;
}
.preview-area img:not(:nth-child(4n)){
margin-right: 1.333%;
}
Javascript
This is the function which is called when files are selected.
2nd line: loop started.
3rd line: create blobURL from file.
4th line: create img element.
6th line: preview after the loop ended.
function preview(elem, output = '') {
Array.from(elem.files).map((file) => {
const blobUrl = window.URL.createObjectURL(file)
output+=`<img src=${blobUrl}>`
})
elem.nextElementSibling.innerHTML = output
}
The full text of source code
In the end, I put the full text of source code.
<style>
.preview-area{
display: flex;
flex-wrap: wrap;
}
.preview-area img{
width: 24%;
margin: 0 0 10px;
object-fit: contain;
}
.preview-area img:not(:nth-child(4n)){
margin-right: 1.333%;
}
</style>
<input type="file" onchange="preview(this)" multiple>
<div class="preview-area"></div>
<script>
function preview(elem, output = '') {
Array.from(elem.files).map((file) => {
const blobUrl = window.URL.createObjectURL(file)
output+=`<img src=${blobUrl}>`
})
elem.nextElementSibling.innerHTML = output
}
</script>
That is all, it was about how to preview multiple images before uploading using javascript.