JAVASCRIPT
Uploading Files to an API with FormData
Learn to securely upload files to a backend API using `FormData` and `fetch`, handling common scenarios like progress tracking and associating metadata.
async function uploadFileToApi(endpoint, file, metadata = {}) {
const formData = new FormData();
formData.append('file', file, file.name);
// Append additional metadata
for (const key in metadata) {
if (Object.prototype.hasOwnProperty.call(metadata, key)) {
formData.append(key, metadata[key]);
}
}
try {
const response = await fetch(endpoint, {
method: 'POST',
body: formData,
// When using FormData, the 'Content-Type' header is automatically
// set to 'multipart/form-data' with the correct boundary by the browser.
// Do NOT set it manually, or boundary will be missing.
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Upload failed: ${response.status} - ${errorText}`);
}
const result = await response.json();
console.log('File uploaded successfully:', result);
return result;
} catch (error) {
console.error('Error during file upload:', error);
throw error;
}
}
// Usage example with an HTML input:
// document.getElementById('fileInput').addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// try {
// const uploadResult = await uploadFileToApi(
// '/api/upload',
// selectedFile,
// { description: 'User profile picture', userId: '123' }
// );
// console.log('Upload finished, response:', uploadResult);
// } catch (error) {
// console.error('Upload failed:', error);
// }
// }
// });
// // HTML part (example):
// // <input type="file" id="fileInput" />
// // <button onclick="document.getElementById('fileInput').click()">Select File to Upload</button>
How it works: This JavaScript snippet demonstrates how to upload files to a backend API using the `FormData` interface and the `fetch` API. `FormData` provides a way to construct key/value pairs representing form fields and their values, including files. When sent via `fetch`, the browser automatically sets the `Content-Type` header to `multipart/form-data` with the correct boundary, which is crucial for server-side processing of file uploads. The function also supports appending additional metadata alongside the file, making it versatile for various upload scenarios.