Sub topic 15
File Inputs and Multipart Uploads
This chapter assumes you know how name and value pairs become submitted data, the difference between GET and POST, and the basics of FormData and fetch. It covers how the browser sends files, what the server receives, and where validation has to happen.
The file input
A file input lets the user pick one or more files from their device. The browser shows its own picker, and you cannot restyle the picker dialog itself.
<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 details matter here:
type="file"creates the control. It is labeled and named like any other control.method="post"is required in practice. File content does not fit in a URL.enctype="multipart/form-data"tells the browser how to encode the body. Without it, the upload does not work.
Why enctype matters
The enctype attribute sets the encoding of the submitted body. Its default is application/x-www-form-urlencoded, which turns every value into text in the form name=value&name2=value2. A file has no useful text form, so with the default encoding the browser sends only the file's name as the value. The content is lost, and nothing warns you.
| Situation | What the server receives |
|---|---|
| POST with `multipart/form-data` | The file name, the content type, and the file bytes |
| POST with the default encoding | Only the file name, as text |
| GET | Only the file name, in the query string |
If a user's uploads arrive as bare file names, check the enctype first.
What a multipart body looks like
With multipart/form-data, the body is split into parts. Each part carries one control's data. The request's Content-Type header names a boundary string that separates the parts, and the browser generates it.
POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----BoundaryX7
------BoundaryX7
Content-Disposition: form-data; name="title"
Holiday photo
------BoundaryX7
Content-Disposition: form-data; name="avatar"; filename="beach.jpg"
Content-Type: image/jpeg
(raw bytes of the file)
------BoundaryX7--Each part has its own headers. Ordinary text controls produce a part with only a name. File controls add a filename and a Content-Type that the browser guesses from the file extension and the operating system's records. The final boundary ends with two extra hyphens.
Attributes that shape the picker
multiple
Adding multiple lets the user choose several files. All the files are sent under the same name, as separate parts. The server must be ready to read a list.
<input id="photos" name="photos" type="file" multiple accept="image/*">accept
accept takes a comma-separated list of file extensions (.pdf), exact MIME types (image/png), or wildcards (image/*). The picker uses it to filter files and preselect a type.
capture
On mobile devices, capture suggests that the browser open the camera or microphone instead of the file picker. Support varies, so treat it as a hint.
required
required works on file inputs. The form will not submit until at least one file is chosen.
Empty file inputs
If the user selects nothing, the browser still sends a part for the control. It has an empty filename and an empty body. The Content-Type is application/octet-stream. Server code must treat an empty file name or zero-length file as "no file", not as an error in parsing. This is different from an unchecked checkbox, which sends nothing at all.
Validation: what the browser does and does not check
The built-in validation attributes treat files differently from text:
requiredworks.acceptdoes not block submission. It filters the picker, but users can often override the filter, for example by choosing "All files". It also does not inspect file contents.minlength,maxlength,pattern,min, andmaxdo not apply to file inputs.- There is no built-in size limit attribute.
Checking size with the Constraint Validation API
You can enforce limits in the browser for a better user experience by combining the files property with setCustomValidity.
<form id="upload-form" action="/upload" method="post" enctype="multipart/form-data">
<label for="avatar">Profile picture (PNG or JPEG, up to 2 MB)</label>
<input id="avatar" name="avatar" type="file" accept="image/png, image/jpeg" required>
<button type="submit">Upload</button>
</form>
<script>
const MAX_BYTES = 2 * 1024 * 1024;
const input = document.querySelector('#avatar');
input.addEventListener('change', () => {
const file = input.files[0];
const tooBig = file && file.size > MAX_BYTES;
input.setCustomValidity(tooBig ? 'The file must be 2 MB or smaller' : '');
input.reportValidity();
});
</script>input.files is a FileList, a read-only, array-like collection of File objects. Each File has name, size (in bytes), type (the MIME type guessed by the browser), and lastModified. With multiple, loop over the list with for (const file of input.files). Use Array.from(input.files) when you need array methods.
You cannot set the value of a file input to a path from script, except to clear it with input.value = ''. This restriction protects user privacy.
Sending files with JavaScript
Calling new FormData(form) includes each selected file as a File entry, so it produces the same multipart body the browser would have built for a normal submission. Passing it to fetch is the usual way to upload without a page reload.
const form = document.querySelector('#upload-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const response = await fetch(form.action, {
method: 'POST',
body: new FormData(form),
});
if (!response.ok) {
console.error('Upload failed with status', response.status);
return;
}
console.log('Upload complete');
});You can also add files that did not come from an input, for example data.append('report', blob, 'report.csv'). The third argument sets the file name. fetch does not report upload progress. If you need a progress bar, use XMLHttpRequest and its upload.onprogress event.
Receiving the upload on the server
Every server stack needs a multipart parser. The example below uses Node.js with Express and the multer package. It limits the size and rejects a missing file. It assumes "type": "module" in package.json.
import express from 'express';
import multer from 'multer';
const upload = multer({
dest: 'uploads/',
limits: { fileSize: 2 * 1024 * 1024 },
});
const app = express();
app.post('/upload', upload.single('avatar'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file received');
}
res.status(201).send(`Stored ${req.file.originalname} (${req.file.size} bytes)`);
});
app.listen(3000);The string 'avatar' must match the control's name. If it does not, the server sees no file, even though the browser sent one. This is the same name-and-value rule as for every other control.
Server-side rules that apply in any language:
- Enforce a maximum size, and set the request body limit at the proxy or web server too.
- Do not use the client's file name as a path. Generate your own name to avoid path traversal and overwriting.
- Check the file's actual content (for example its magic bytes), not only the declared type.
- Store uploads outside the web root, or serve them with a safe
Content-Type.
Common errors
| Symptom | Likely cause |
|---|---|
| Server receives only a file name | Missing `enctype="multipart/form-data"` |
| Server receives no file field | Missing `name` on the input, or a mismatched name |
| Upload works in the browser but not with `fetch` | A hand-written `Content-Type` header |
| Only one file arrives from a `multiple` input | Server reads a single value instead of a list |
| Large files fail with 413 | A proxy or server body limit is lower than your own |
Exercise
A form has <input type="file" name="resume"> and method="post", but no enctype. The server logs show resume=cv.pdf and no file content. What is wrong, and what is the fix?
Show answer
The form uses the default application/x-www-form-urlencoded encoding, which sends only the file name as text. Add enctype="multipart/form-data" to the form so the browser sends the file bytes as a multipart part.
Exercise
You add accept="image/png" and a client-side 2 MB check. Why must the server still validate the upload?
Show answer
Both checks run in the client and can be bypassed. A user can pick "All files" in the picker, edit the page, or send a request directly. The server must enforce its own size limit and check the file's real type and content.