File API
The File API enables web applications to read files (and their contents) stored on the user's computer. This is typically done when a user selects files via an <input type="file"> element or by drag-and-drop.
1. Accessing Files
Files are accessed using the FileList object, which is returned by the files property of an <input> element.
<input type="file" id="fileInput" multiple>
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', (event) => {
const fileList = event.target.files;
console.log(fileList); // A FileList object
for (const file of fileList) {
console.log(`Name: ${file.name}`);
console.log(`Size: ${file.size} bytes`);
console.log(`Type: ${file.type}`);
}
});
2. The FileReader Object
To read the actual content of a file, you use the FileReader object. It works asynchronously and fires events when reading is complete.
Reading Text
const reader = new FileReader();
reader.onload = function(e) {
const text = e.target.result;
console.log(text);
};
reader.readAsText(file);
Reading Images (Data URL)
Useful for previewing images before uploading.
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement("img");
img.src = e.target.result; // e.g., "data:image/jpeg;base64,..."
document.body.appendChild(img);
};
reader.readAsDataURL(file);
3. Object URLs
An alternative to FileReader for previews is URL.createObjectURL(). It creates a temporary URL representing the file object. This is generally more efficient than reading the file into a base64 string.
const objectURL = URL.createObjectURL(file);
const img = document.createElement("img");
img.src = objectURL;
document.body.appendChild(img);
// Clean up memory when done
img.onload = () => {
URL.revokeObjectURL(objectURL);
};
programming/javascript/vanilla/javascript programming/javascript/vanilla/typed-arrays programming/javascript/vanilla/dom-manipulation