FileReader and Blob

A Blob is an immutable chunk of bytes with a MIME type and a size; blob.slice() cuts pieces without copying. A File is a Blob with a name and lastModified, from <input type="file">, drag and drop (dataTransfer.files) or the pickers in File System Access. Read a blob with the promise methods text(), arrayBuffer(), bytes() and stream(), or with the older event-based FileReader, which still offers readAsDataURL(). URL.createObjectURL(blob) makes a blob: URL for src or href until URL.revokeObjectURL(). The File API is Baseline Widely available; bytes() came last (Chrome 144 1 ). The demo simulates a user's choice:

Checking and reading a chosen fileHTMLLive
<input type="file" id="pick"><pre id="out"></pre>
<script type="module">
  const log = (...parts) => (out.textContent += parts.join(' ') + '\n');
  pick.addEventListener('change', async () => {
    const [file] = pick.files;                      // a File is a Blob with a name
    log(file.name, file.type, file.size, 'bytes |', await file.slice(7).text());
    log('bytes():', (await file.bytes()).slice(0, 5).join(' '));
    const reader = new FileReader();                // older event-based API
    reader.onload = () => log('readAsDataURL:', reader.result);
    reader.readAsDataURL(file);
  });
  const picked = new DataTransfer();                // simulate the user's choice
  picked.items.add(new File(['Hello, Blob!'], 'hello.txt', { type: 'text/plain' }));
  pick.files = picked.files;
  pick.dispatchEvent(new Event('change'));
</script>
Browser output of Listing 9.20
Browser output of 20

Check size before reading. type is guessed from the file extension, so validate uploads again on the server.