Sending Form Data: multipart/form-data Uploads
You'll learn how to upload files and traditional form fields together using the Fetch API and FormData objects.
What Is multipart/form-data?
When you need to send files (like images or documents) along with other form fields to a server, you use a special encoding called multipart/form-data. Unlike JSON, which is text-based, this format can handle binary data like images, PDFs, or videos.
Think of it like packing a box for shipping: JSON is like writing everything on paper, but multipart is like putting different items (papers, photos, objects) into separate compartments in the same box.
The FormData Object
JavaScript provides the FormData object to build multipart requests easily. It automatically sets the correct content type and encoding.
// Create a new FormData object
const formData = new FormData();
// Add text fields
formData.append('username', 'john_doe');
formData.append('email', 'john@example.com');
// Add a file from an input element
const fileInput = document.querySelector('input[type="file"]');
formData.append('profilePic', fileInput.files[0]);
// Send with fetch
fetch('/upload', {
method: 'POST',
body: formData
// Note: Do NOT set Content-Type header manually
// Browser sets it automatically with boundary
});
Why It Works
When you pass FormData as the body, the browser automatically sets the Content-Type header to multipart/form-data with a special boundary marker that separates each field. This tells the server how to parse the different parts of your upload.
Key Takeaway: Use FormData objects with fetch() to upload files and form data together—the browser handles the multipart encoding automatically, and you never manually set the Content-Type header for multipart uploads.