Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Previewing Uploaded Files | Storage, File Handling, and Geolocation
JavaScript Web APIs Essentials

bookPreviewing Uploaded Files

index.html

index.html

style.css

style.css

script.js

script.js

copy

Displaying image previews before uploading is a common requirement in modern web applications. The example above uses the FileReader API to achieve this entirely on the client side. When you select one or more image files, the script listens for changes to the file input. It then loops through each selected file, checks if the file is an image by inspecting its type property, and creates a new FileReader for each file.

The FileReader reads the file as a data URL using readAsDataURL. When the file has been read, the onload event fires, and the result is a base64-encoded data URL. This data URL is set as the src of a new img element, which is then added to the preview container in the DOM. Because the code uses a loop, it can handle multiple files at once, showing a preview for each selected image. This approach ensures you can view your images before uploading, without sending any data to the server.

question mark

What is the main use of the FileReader API in the context of file uploads?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 4

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

bookPreviewing Uploaded Files

Glissez pour afficher le menu

index.html

index.html

style.css

style.css

script.js

script.js

copy

Displaying image previews before uploading is a common requirement in modern web applications. The example above uses the FileReader API to achieve this entirely on the client side. When you select one or more image files, the script listens for changes to the file input. It then loops through each selected file, checks if the file is an image by inspecting its type property, and creates a new FileReader for each file.

The FileReader reads the file as a data URL using readAsDataURL. When the file has been read, the onload event fires, and the result is a base64-encoded data URL. This data URL is set as the src of a new img element, which is then added to the preview container in the DOM. Because the code uses a loop, it can handle multiple files at once, showing a preview for each selected image. This approach ensures you can view your images before uploading, without sending any data to the server.

question mark

What is the main use of the FileReader API in the context of file uploads?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 4
some-alt