JAVASCRIPT
Handling File Uploads to APIs with JavaScript FormData
Learn how to seamlessly upload files, including images and documents, to a web API using JavaScript's `FormData` object, mimicking a standard HTML form submission.
async function uploadFile(apiUrl, file, additionalFields = {}) {
const formData = new FormData();
// Append the file(s)
formData.append('file', file, file.name); // 'file' is the field name expected by your API
// Append any additional text fields
for (const key in additionalFields) {
if (Object.hasOwnProperty.call(additionalFields, key)) {
formData.append(key, additionalFields[key]);
}
}
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: formData, // FormData automatically sets 'Content-Type': 'multipart/form-data'
// headers: {
// 'Authorization': 'Bearer YOUR_AUTH_TOKEN', // Add if your API requires authentication
// }
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`Upload failed! Status: ${response.status}, Details: ${JSON.stringify(errorData)}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('File upload error:', error);
throw error;
}
}
// Example Usage (assuming you have an input type="file" element):
// const fileInput = document.querySelector('#myFileInput');
// fileInput.addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// try {
// const result = await uploadFile('https://api.example.com/upload', selectedFile, {
// description: 'User profile picture',
// userId: '123'
// });
// console.log('Upload successful:', result);
// } catch (error) {
// console.error('Upload failed:', error);
// }
// }
// });
How it works: This JavaScript snippet demonstrates how to upload files to an API endpoint using the `FormData` object. `FormData` allows you to construct a set of key/value pairs representing form fields and their values, including files. When used with `fetch`, `FormData` automatically sets the `Content-Type` header to `multipart/form-data`, which is the standard for file uploads. It also supports appending additional text fields alongside the file, making it versatile for various upload scenarios.