The FileList object in modern JavaScript is a web API that represents an immutable list of file objects, typically generated when a user selects files using an element or via a drag-and-drop operation.
Here is a comprehensive guide to understanding and mastering the FileList object. Key Characteristics of FileList
Array-Like, Not an Array: It has a .length property and indexed elements (e.g., list[0]), but it lacks native array methods like .map(), .forEach(), or .filter().
Read-Only: You cannot directly add, remove, or replace files inside a FileList object.
Contains File Objects: Each item inside the list is a standard JavaScript File object containing metadata like name, size, type, and lastModified. How to Obtain a FileList
There are two primary ways to get a FileList object in the browser. 1. Via File Input
When a user selects files through an input field (especially one with the multiple attribute), the browser stores them in the input’s .files property. Use code with caution. javascript
const filePicker = document.getElementById(‘filePicker’); filePicker.addEventListener(‘change’, (event) => { const fileList = event.target.files; // This is the FileList object console.log( Use code with caution. 2. Via Drag and DropYou selected ${fileList.length} files.); });
When a user drops files onto a designated drop zone, the FileList is accessible via the event’s dataTransfer property. javascript
const dropZone = document.getElementById(‘dropZone’); dropZone.addEventListener(‘drop’, (event) => { event.preventDefault(); // Prevent browser from opening the file const fileList = event.dataTransfer.files; // This is the FileList object console.log(fileList); }); Use code with caution. Working with FileList: Essential Patterns
Because FileList is not a true array, trying to run fileList.forEach() will throw a TypeError. Use these modern patterns to work with it efficiently. Converting FileList to a True Array
Converting the list into a standard array unlocks all native array manipulation methods. javascript
const fileList = filePicker.files; // Approach A: Array.from() (Recommended for readability) const fileArray1 = Array.from(fileList); // Approach B: Spread Operator const fileArray2 = […fileList]; // Now you can use array methods freely: fileArray1.forEach(file => console.log(file.name)); const largeFiles = fileArray1.filter(file => file.size > 10241024); Use code with caution. Traditional Looping (Without Conversion)
If you prefer not to create a new array in memory, you can loop through it using a standard for or for…of loop. javascript
// Using for…of for (const file of filePicker.files) { console.log( Use code with caution. Reading Files within a FileListFile Name: ${file.name}, Size: ${file.size} bytes); } // Using a standard for loop with the .item() method const list = filePicker.files; for (let i = 0; i < list.length; i++) { const file = list.item(i); // Equivalent to list[i] console.log(file.name); }
Once you target a File inside the FileList, you must use modern browser APIs to read or upload its content. 1. Creating Previews (Object URLs)
For client-side rendering (like image previews), creating a temporary blob URL is the most performant approach. javascript
const file = filePicker.files[0]; if (file && file.type.startsWith(‘image/’)) { const previewUrl = URL.createObjectURL(file); document.getElementById(‘myImage’).src = previewUrl; // Clean up memory when the image is loaded or no longer needed document.getElementById(‘myImage’).onload = () => URL.revokeObjectURL(previewUrl); } Use code with caution. 2. Reading Text or Binary Data (FileReader or Blobs)
Modern browsers allow you to treat File objects as Blob types, meaning you can call methods like .text() or .arrayBuffer() directly on them using async/await. javascript
const file = filePicker.files[0]; async function readFile(file) { try { const textContent = await file.text(); console.log(“File content:”, textContent); } catch (error) { console.error(“Error reading file:”, error); } } Use code with caution. Advanced: Programmatically Modifying Files
Because FileList is read-only, you cannot write filePicker.files.pop() to remove a file. To programmatically add or remove items from an input element, you must use the DataTransfer API to construct a brand new file list. Example: Removing a specific file from an input field javascript
function removeFileByIndex(inputElement, indexToRemove) { const dt = new DataTransfer(); const { files } = inputElement; for (let i = 0; i < files.length; i++) { if (i !== indexToRemove) { dt.items.add(files[i]); // Keep all files except the one being removed } } // Reassign the newly constructed FileList back to the input inputElement.files = dt.files; } Use code with caution.
Leave a Reply