Sub topic 15
File inputs and multipart uploads
This chapter assumes you know how a form's method and enctype affect a submission, how name attributes become submitted fields, and how to label a control. It covers the file input, why uploads need a different encoding, and how to read the selected files in JavaScript.
The file input
An <input type="file"> lets the user pick one or more files from their device. The browser shows its own picker, and you cannot set the selected file from markup or script for security reasons.
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="avatar">Profile picture</label>
<input id="avatar" name="avatar" type="file" accept="image/png, image/jpeg">
<button type="submit">Upload</button>
</form>Three attributes matter most:
acceptis a comma-separated list of MIME types, extensions, or wildcards such asimage/*. It filters the picker but does not enforce anything. Users can still choose other files, so the server must check them.multipleallows more than one file under the samename.capturehints that a mobile device should open the camera or microphone instead of the file picker.
Why `enctype` matters
The default encoding, application/x-www-form-urlencoded, turns every value into text. For a file input it would send only the file name, not the contents. To send the contents, set enctype="multipart/form-data" on a form that uses method="post".
A multipart body is split into parts by a boundary string. Each part has its own headers and body.
The server receives each part with its field name, so a text field and a file can travel in one request. A GET form cannot upload files, because the browser sends only the file name in the query string.
Reading files in JavaScript
The input's files property is a FileList. Each item is a File object with name, size, type, and lastModified. You can check these before submitting.
const input = document.querySelector('#avatar');
const maxBytes = 2 * 1024 * 1024;
input.addEventListener('change', () => {
const file = input.files[0];
if (!file) return;
if (file.size > maxBytes) {
input.setCustomValidity('Choose a file smaller than 2 MB');
} else {
input.setCustomValidity('');
}
input.reportValidity();
});To send the form without leaving the page, pass it to FormData. The browser builds the multipart body for you.
const form = document.querySelector('form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const response = await fetch(form.action, {
method: 'POST',
body: new FormData(form),
});
console.log(response.status);
});Do not set the Content-Type header yourself in this case. The browser adds it together with the boundary, and a manual value would omit the boundary and break parsing on the server.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Server sees only a file name | Missing `enctype` | Add `enctype="multipart/form-data"` |
| Only one file arrives | Missing `multiple` | Add `multiple` to the input |
| Server rejects the body as malformed | `Content-Type` set manually in `fetch` | Remove the header |
| Wrong file types accepted | `accept` treated as validation | Validate type and size on the server |
An empty file input still submits a part with an empty file name, so the server should treat that case as "no file".
Exercise
A form with a file input and method="post" submits successfully, but the server reports that the uploaded "file" is a short text string such as photo.jpg. What is wrong, and what is the fix?
Show answer
The form uses the default urlencoded encoding, which sends only the file name as text. Add enctype="multipart/form-data" to the form element so the browser sends the file contents as a multipart part.
Exercise
You call fetch with a FormData body and also set the header "Content-Type: multipart/form-data". Why does the server fail to parse the body?
Show answer
The manual header has no boundary parameter, so the server cannot find where each part starts and ends. Leave the header unset and the browser will add it with the correct boundary.