JAVASCRIPT
Uploading Files and Form Data to an API using FormData
Efficiently send multipart/form-data including files and input fields to a backend API using JavaScript's FormData object and Fetch API.
async function uploadFileAndData(url, file, additionalData = {}) {
const formData = new FormData();
// Append the file
formData.append('file', file, file.name);
// Append additional text data
for (const key in additionalData) {
formData.append(key, additionalData[key]);
}
try {
const response = await fetch(url, {
method: 'POST',
// No 'Content-Type' header needed here; Fetch API sets it automatically for FormData
body: formData
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
const result = await response.json();
return result;
} catch (error) {
console.error("Error uploading data:", error);
throw error;
}
}
// Example usage with an HTML input type="file":
/*
const fileInput = document.querySelector('#myFileInput');
const submitButton = document.querySelector('#submitButton');
submitButton.addEventListener('click', async () => {
if (fileInput.files.length > 0) {
const selectedFile = fileInput.files[0];
const extraInfo = { description: 'A user-uploaded image', category: 'photos' };
try {
const uploadResult = await uploadFileAndData('https://api.example.com/upload', selectedFile, extraInfo);
console.log('Upload successful:', uploadResult);
} catch (error) {
console.error('Upload failed:', error);
}
} else {
console.log('Please select a file to upload.');
}
});
*/
How it works: This code snippet demonstrates how to upload files and associated form data to an API using the `FormData` object. The `FormData` interface allows you to construct a set of key/value pairs representing form fields, which can then be easily sent via `fetch` as a `multipart/form-data` request. It correctly appends both a file (from an `input type="file"`) and arbitrary additional text data. A key detail is that you should not manually set the `Content-Type` header when sending `FormData`, as `fetch` handles it automatically, including the necessary boundary string.