JAVASCRIPT
Upload Files and Form Data with Fetch API
Learn to send various types of form data, including files, to a backend API endpoint using the browser's native `fetch` API and the `FormData` object in JavaScript.
async function uploadFileWithFormData(file, additionalData) {
const formData = new FormData();
formData.append('profilePicture', file, file.name); // 'profilePicture' is the field name on the server
// Append additional non-file data
for (const key in additionalData) {
formData.append(key, additionalData[key]);
}
try {
const response = await fetch('https://api.example.com/upload', {
method: 'POST',
body: formData, // FormData automatically sets 'Content-Type': 'multipart/form-data'
// Do NOT manually set 'Content-Type' header when using FormData,
// the browser handles it correctly including the boundary.
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('Upload successful:', result);
return result;
} catch (error) {
console.error('Error uploading file:', error);
throw error;
}
}
// Example usage (e.g., from an <input type="file"> change event):
// const fileInput = document.getElementById('fileUpload');
// fileInput.addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// const userData = {
// userId: 'user123',
// description: 'User profile picture'
// };
// try {
// await uploadFileWithFormData(selectedFile, userData);
// alert('File uploaded successfully!');
// } catch (error) {
// alert('File upload failed.');
// }
// }
// });
How it works: This JavaScript snippet demonstrates how to upload files and accompanying form data to a server using the `FormData` object and the `fetch` API. `FormData` allows you to construct a set of key/value pairs representing form fields, including files. When sent via `fetch`, the browser automatically sets the `Content-Type` header to `multipart/form-data` with the correct boundary, which is the standard for file uploads. It also shows how to append non-file data along with the file.