ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
AJAX & Fetch API Tutorial• 6 min read
FormData & Asynchronous File Uploads
Uploading binary images, PDFs, and multi-part form data with fetch
Uploading files and binary data asynchronously is accomplished using the FormData object.
The FormData Content-Type Rule
new FormData() automatically sets the correct multipart/form-data encoding and boundary strings.
CRITICAL RULE: Do NOT manually set the "Content-Type" header when passing a FormData object to fetch(). Let the browser set it automatically with the boundary string!
Uploading an Avatar Image
async function uploadAvatar(fileInput) {
const file = fileInput.files[0];
const formData = new FormData();
formData.append("avatar", file);
formData.append("userId", "user_982");
// Note: Do NOT set Content-Type header manually here!
const res = await fetch("/api/upload/avatar", {
method: "POST",
body: formData
});
return await res.json();
}The browser automatically attaches the multipart boundary header.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
What happens if you manually set `headers: { "Content-Type": "multipart/form-data" }` when using `FormData` with `fetch()`?