Explain Codes LogoExplain Codes Logo

Html <input type='file'> File Selection Event

html
responsive-design
file-api
file-input
Alex KataevbyAlex Kataev·Sep 30, 2024
TLDR

Capture the change event on an <input type='file'> to initiate actions after file selection. Here's how to do it with JavaScript:

document.querySelector('input[type=file]').onchange = function() { alert(`Eureka! File located: ${this.files[0].name}`); };

The handler is attached directly to the input field, which uses the files array to access the selected file's details. This concise script informs the user of the file they just selected.

Solid foundations: Building your file input

Using the file input element allows users to upload files to your website. To guarantee robust file uploads, you need to master the following essentials:

Setting up the input and listening for changes

Your file input (<input type="file" id="myFile">) is waiting for action. Trigger JavaScript to react to the change event:

const fileInput = document.getElementById('myFile'); fileInput.addEventListener('change', (e) => { const fileInfo = e.target.files[0]; console.log(`You picked: ${fileInfo.name}`); });

This logs the selected file's name in the console.

Clean it up, keep it fresh

Clear the input's value to ensure your change event fires for re-selecting the same file:

fileInput.addEventListener('change', (e) => { // process e.target.files[0] fileInput.value = ''; // Reset the field. Keep it clean! });

More the merrier: handling multiple selections

If your input permits multiple file selections, loop through the files array like a boss:

fileInput.addEventListener('change', (e) => { Array.from(e.target.files).forEach(file=> console.log(file.name)); });

This logs all selected file names in the console.

Utilizing the input's attributes to enhance form handling

The required attribute ensures a user must select a file before form submission. Setting enctype="multipart/form-data" processes the file data properly.

Enforcing rules and providing feedback

Enforce file size or type limits and provide clear feedback when users break the rules.

fileInput.addEventListener('change', (e) => { const file = e.target.files[0]; if(file.size > maxSize) { alert('This file is heavier than a sumo wrestler! Choose lighter.'); fileInput.value = ''; // Input cleared. There's always a second chance! } });

Add flair with CSS animation

Add a touch of CSS to provide animated feedback when users exceed limits. Why not turn audits into a fun experience?

From basic to boss: mastering complex situations

Ready to level up? Here are some advanced techniques and considerations:

Implementing Drag-and-Drop

Turn file selection into a game of catch with drag-and-drop:

<div id="dropZone">Drop files here</div>

Listen for dragover and drop events to catch those flying files.

Showing image previews with File API

A picture is worth a thousand words. Show a preview for image files:

fileInput.addEventListener('change', (e) => { const file = e.target.files[0]; const reader = new FileReader(); reader.onload = (e) => { document.getElementById('preview').src = e.target.result; }; reader.readAsDataURL(file); });

Ensuring accessibility and security

Ensure file input is accessible, consider keyboard navigability, and always validate file uploads server-side to prevent unsavory surprises.