[Javascript]How to preview an image before uploading

preview image



In this article,  I am going to describe about how to preview an image before uploading using javascript.


I have prepared a Demo which can be touched at the lower.





HTML

6th line is input[type=’file’] which has onchange attribute and preview function will be called when a file selected.
7th line is the preview area.
1st ~ 4th line is the style for the preview area.

<style>
    .preview-area{ width: 300px; }
    .preview-area img{ width: 100%; }
</style>

<input type="file" onchange="preview(this)">
<div class="preview-area"></div>





Javascript

As we pass a file to createObjectURL method as below, it will create blobURL.
And by setting the blobURL to src attribute of image tag, the image will be displayed on the blowser.

function preview(elem){
    const blobUrl = window.URL.createObjectURL(elem.files[0])
    elem.nextElementSibling.innerHTML = `<img src=${blobUrl}>`
}





Demo

I have prepared a Demo which can be touched.
Preview image will be displayed when a file is selected.

We can put input[type=’file’] as many as we like.






The full text of source code

In the end, I put the full text of source code.

<style>
    .preview-area{ width: 300px; }
    .preview-area img{ width: 100%; }
</style>

<input type="file" onchange="preview(this)">
<div class="preview-area"></div>

<input type="file" onchange="preview(this)">
<div class="preview-area"></div>


<script>
    function preview(elem){
        const blobUrl = window.URL.createObjectURL(elem.files[0])
        elem.nextElementSibling.innerHTML = `<img src=${blobUrl}>`
    }
</script>







That is all, it was about how to preview an image before uploading using javascript.

You can subscribe by SNS

Sponcerd Link

Popular Posts