Handling File Uploads with FormData
What you'll learn: How to include files from file inputs in FormData objects for uploading to a server.
When users select files through <input type="file"> elements, those files need special handling to be sent to the server. The browser represents selected files as File objects, and FormData is designed to handle them seamlessly for multipart/form-data submissions.
Including Files in FormData
When you append a File object to FormData, it automatically configures the request for file upload. You can access files from a file input using the files property:
const formElement = document.querySelector('form');
const fileInput = document.querySelector('input[type="file"]');
formElement.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData();
// Get the selected file
const file = fileInput.files[0];
if (file) {
formData.append('avatar', file);
formData.append('username', 'john_doe');
fetch('/upload', {
method: 'POST',
body: formData
// No Content-Type header needed - browser sets it automatically
});
}
});
Multiple Files
For inputs with the multiple attribute, loop through all selected files:
const files = fileInput.files;
for (let i = 0; i < files.length; i++) {
formData.append('photos', files[i]);
}
The File object contains useful properties like name, size, and type that you can check before uploading. FormData handles the binary data encoding automatically when you submit.
Key Takeaway: FormData's append() method accepts File objects directly, automatically setting up multipart/form-data encoding for file uploads without manual configuration.