JAVASCRIPT
Uploading Files to an API with FormData in JavaScript
Learn to send files, such as images or documents, to a backend API using JavaScript's Fetch API and the FormData object, perfect for file uploads.
async function uploadFile(url, file, additionalData = {}) {
try {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name the API expects
// Append any additional data fields
for (const key in additionalData) {
if (Object.prototype.hasOwnProperty.call(additionalData, key)) {
formData.append(key, additionalData[key]);
}
}
const response = await fetch(url, {
method: 'POST',
// When using FormData, the 'Content-Type' header is automatically set to 'multipart/form-data'
// and includes the correct boundary, so DO NOT set it manually.
body: formData
});
if (!response.ok) {
const errorText = await response.text(); // Get raw text for potential non-JSON errors
throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorText || response.statusText}`);
}
const result = await response.json();
console.log('File upload successful:', result);
return result;
} catch (error) {
console.error('Error uploading file:', error.message);
throw error;
}
}
// Example usage (assuming an HTML input type="file" element with id="fileInput"):
// const fileInput = document.getElementById('fileInput');
// if (fileInput) {
// fileInput.addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// const uploadUrl = 'https://api.example.com/upload';
// const metadata = { description: 'User profile picture', category: 'image' };
// uploadFile(uploadUrl, selectedFile, metadata)
// .then(res => console.log('Upload complete:', res))
// .catch(err => console.error('Upload failed:', err));
// }
// });
// }
How it works: This snippet demonstrates how to upload a file (e.g., from a `<input type="file">` element) to an API using JavaScript's `fetch` API and `FormData`. `FormData` allows constructing a set of key/value pairs representing form fields, including files, which is then sent as a `multipart/form-data` request. Crucially, the `Content-Type` header is automatically set by the browser when `FormData` is used, so it should not be manually defined.