File, Blob and the security model

The browser gives a page no access to the user's disk. A file reaches your code as a File object only when the user picks it in the file dialog or drops it onto the page. The content is not read right away: the object is just a reference.

  • A Blob is immutable raw data with a type (type) and a size (size).
  • A File is a subclass of Blob that adds name and lastModified.
  • FileReader is the older event-based reading API, while Promise methods such as file.text() are the new way.
The flow of reading a chosen file
The flow of reading a chosen file

💡 Node.js 20+ also has Blob and File, so many examples can be tried without a browser.


input[type=file] and validation

An input is enough to pick a file. multiple allows several files and accept filters the picker.

html
<input type="file" id="file" accept="image/*,.pdf" multiple>

The chosen files are in input.files inside the change event. Suppose two files were chosen:

javascript
const input = document.querySelector('#file');

input.addEventListener('change', () => {
  const files = input.files;
  for (const file of files) {
    console.log(file.name, file.type, file.size);
  }
});

Validate first, then process: type and size.

javascript
const MAX_SIZE = 2 * 1024 * 1024;
const ALLOWED = ['image/png', 'image/jpeg'];

function validate(file) {
  if (!ALLOWED.includes(file.type)) return `type ${file.type} not allowed`;
  if (file.size > MAX_SIZE) return 'file is too large';
  return null;
}