File API lets web‑apps read, slice, stream and upload local files entirely in the browser—without server round‑trips until you decide.
Blob
plus name
, lastModified
.File
.Blob/File
to text, DataURL or ArrayBuffer.Note: All tasks are asynchronous by design—UI remains responsive while I/O occurs on a background thread.
<input type="file" id="pick" multiple accept="image/*">
Attribute | Description |
---|---|
multiple | Allow multi‑selection (returns FileList ) |
accept | MIME(s)/extensions filter (e.g. image/* , .pdf ) |
capture | Mobile hint to open camera/mic (environment |user ) |
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
const files = [...e.dataTransfer.files]; // ← FileList → Array
});
name: string
— base filename (no path)type: string
— MIME (e.g. image/png
)size: number
— byteslastModified: DOMTimeStamp
— epoch msblob.slice([start], [end], [contentType]) | Returns a new Blob with byte‑range [start, end) |
---|---|
blob.stream() | ReadableStream for progressive reading (large files) |
blob.arrayBuffer() | Promise → ArrayBuffer |
blob.text() | Promise → string (UTF‑8 by default) |
const reader = new FileReader();
reader.onload = ({ target }) => console.log(target.result);
reader.onerror = ({ target }) => console.error(target.error);
reader.readAsText(file, 'utf-8');
Method | Parameters | Result (reader.result ) |
---|---|---|
readAsText(blob, [encoding]) |
|
string |
readAsArrayBuffer(blob) | ArrayBuffer |
|
readAsDataURL(blob) | data:<mime>;<base64> |
Note: Prefer the promise‑based blob.text()
/arrayBuffer()
when you don’t need legacy IE support.
// first 1 MiB
const slice = file.slice(0, 1 * 1024 * 1024);
const text = await slice.text();
for await (const chunk of file.stream()) {
processChunk(chunk); // Uint8Array
}
Tip: Streams keep memory usage flat—vital for multi‑GB video editing in browser.
const fd = new FormData();
fd.append('avatar', file, file.name);
await fetch('/upload', {
method: 'POST',
body: fd
});
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) updateBar(e.loaded / e.total);
};
xhr.open('POST', '/upload');
xhr.send(fd);
multipart/form-data
with proper boundary.const writable = await fileHandle.createWritable();
await writable.write(blob);
await writable.close();
Note: These APIs are origin‑private; they cannot access arbitrary OS paths.
file.type
; sniff server‑side.Web Workers
for CPU‑heavy parsing (e.g., ZIP).requestIdleCallback
to batch UI updates while reading.Class | Key Methods | Return Type |
---|---|---|
Blob | arrayBuffer() | Promise<ArrayBuffer> |
File | slice(start,end) | Blob |
FileReader | readAsDataURL() | void |
FileSystemFileHandle | createWritable() | Promise<WritableStream> |