Preview an image before uploading it – HTML DOM

We prepare the markup for a file input which allows to choose an image, and an img element for previewing the selected file.

<

input

type

=

"

file

"

id

=

"

fileInput

"

/>



<

img

id

=

"

preview

"

/>

Both elements can be taken by the getElementById() method:

const

fileEle

=

document

.

getElementById

(

'fileInput'

)

;


const

previewEle

=

document

.

getElementById

(

'preview'

)

;

1. Use the URL.createObjectURL() method

fileEle

.

addEventListener

(

'change'

,

function

(

e

)

{



const

file

=

e

.

target

.

files

[

0

]

;




const

url

=

URL

.

createObjectURL

(

file

)

;




previewEle

.

src

=

url

;


}

)

;

2. Use the FileReader’s readAsDataURL() method

fileEle

.

addEventListener

(

'change'

,

function

(

e

)

{



const

file

=

e

.

target

.

files

[

0

]

;



const

reader

=

new

FileReader

(

)

;


reader

.

addEventListener

(

'load'

,

function

(

)

{



previewEle

.

src

=

reader

.

result

;


}

)

;



reader

.

readAsDataURL

(

file

)

;


}

)

;

See also