File Inputs and Uploads

Intermediate · 13 min

How input type=file picks files, why a form needs enctype multipart/form-data to send them, what accept does not enforce, and how to read files in JavaScript.

Before thisAutocomplete and Input Modes

James Q Quick · 13 min

File Inputs and Uploads

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by James Q QuickReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `<input type="file">` opens the system file picker. `multiple` allows several files, and the chosen files are available in JavaScript as `input.files`, a list of `File` objects with `name`, `size` and `type`.
  • A form sends a file's contents only with `enctype="multipart/form-data"`. In a test, the default encoding sent just the filename (`up=a.txt`), while the multipart form carried the file's bytes.
  • `accept` is a hint for the picker, not a rule. In a test, a `.txt` file was accepted by an input with `accept=".png,image/*"` and the field was valid.
  • `required` works: an empty required file input is `valueMissing`. But the browser knows nothing about size limits, so check the size in JavaScript and, always, on the server.
  • A script cannot set a file input's value, and `input.value` shows a fake path (`C:\fakepath\a.txt`). To show a preview, read `input.files[0]` with `URL.createObjectURL` or `FileReader`.

Why files are different

Every other form control produces a short piece of text. A file is bytes, possibly millions of them, with a name and a type. The browser also cannot let a page read the user’s disk at will, so files are handled through a control the user must operate: the file input.

<form action="/upload" method="post" enctype="multipart/form-data">
  <label for="photo">Photo</label>
  <input id="photo" name="photo" type="file" accept="image/*" required>
  <button>Upload</button>
</form>

name and <label> work as for any control. The new parts are accept, multiple and the encoding on the form.

The encoding is not optional

The default form encoding, application/x-www-form-urlencoded, turns every field into name=value text. For a file, “value” is the filename. I tested a form with a file input and no enctype in headless Chromium, Firefox and WebKit: the server received up=a.txt and no content. The same form with enctype="multipart/form-data" sent a multipart body that included the file’s content in all three.

Multipart splits the body into parts, one per field, each with its own headers, so binary data can sit beside text. It is also what the forms lesson pointed to. Forgetting it is the most common reason an upload “works” but arrives empty. The server side of the story, including storing files, is in file uploads and object storage.

accept, multiple and required

accept takes file extensions and media types: accept=".pdf,.docx" or accept="image/*". It changes what the picker shows by default and nothing more. In a test, a plain text file was set on an input with accept=".png,image/*", and input.files.length was 1 and validity.valid true. Users can change the picker’s filter, and a script or curl ignores it. Treat it as a convenience.

multiple lets the user choose several files. In a test, two files came back as a.txt:2 and b.txt:4 (name and size in bytes) from input.files. required works as expected: an empty required file input had validity.valueMissing true. capture asks mobile browsers to use the camera; I could not test it without a device. webkitdirectory selects a folder; web-features 3.47.0 lists it as newly available, not widely.

Reading files in JavaScript

input.files is a FileList of File objects, each with name, size, type and lastModified. You can validate before upload:

input.addEventListener("change", () => {
  const file = input.files[0];
  if (file && file.size > 2 * 1024 * 1024) {
    input.setCustomValidity("Please choose a file under 2 MB");
  } else {
    input.setCustomValidity("");
  }
});

That reuses the constraint validation API. For a preview, URL.createObjectURL(file) gives a temporary URL for an <img> or <video>, and FileReader reads the contents. To send files with fetch, build a FormData and append the file; the browser sets the multipart header for you, so do not set Content-Type yourself.

The fake path and why you cannot set a value

Reading input.value gave C:\fakepath\a.txt in all three browsers. The real path is hidden so a page cannot learn the user’s folder names. Setting value to a non-empty string throws InvalidStateError, as a test confirmed, because otherwise a page could choose files for the user. Only an empty string (to clear the input) is allowed. Playwright and other test tools set files through the browser’s automation layer, not through value.

Do not trust the client

Client checks improve feedback only. The server must check size, type (by content, not by filename or the type the client reports), and the destination path, and should store files away from where code runs. Size limits belong in the server and any proxy as well.

What the video covers

The embed is the whole of James Q Quick’s “HTML File Uploads in 5 Minutes (Plus Some JavaScript Features)” (October 2023). Its description says it covers uploading files with the file input type and multipart form-data, and adds JavaScript to preview a video. The title says five minutes and it runs nearly thirteen, and there are no chapters. I could not read a transcript. The accept, validity, fake-path and encoding results above are mine and were run in headless Chromium, Firefox and WebKit using automation to set files; I did not test a real file picker or capture.

Where this fits

This follows autocomplete and input modes. The last forms lesson is progress, meter and output, which includes showing upload progress.

Check yourself

  1. 01Your upload form posts, but the server only receives the filename. What did you forget?

    `enctype="multipart/form-data"` on the `<form>` (and `method="post"`). The default `application/x-www-form-urlencoded` encoding has no way to carry file contents. In a test it sent `up=a.txt` and nothing else.

  2. 02An input has `accept="image/*"`. Can you trust that only images arrive?

    No. `accept` only filters what the file picker shows by default, and users can switch the filter or drag in anything. In a test, a text file was accepted and the field reported valid. Check the type and size in JavaScript for feedback and again on the server.

  3. 03How do you show a thumbnail of the chosen image before upload?

    Listen for `change`, take `input.files[0]` and set an image's `src` to `URL.createObjectURL(file)` (or read it with `FileReader`). The file never leaves the browser until the form is submitted.

  4. 04Why can't you pre-fill a file input with `input.value = 'photo.jpg'`?

    It would let a page choose files from the user's disk. Setting a non-empty value throws an `InvalidStateError` (it did in a test), and reading `value` gives a fake path that hides the real folder.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark