JAVASCRIPT
Uploading Files to API with FormData in JavaScript
Discover how to efficiently upload files to a backend API using JavaScript's `FormData` object with the `fetch` API, enabling seamless file transfers in web applications.
async function uploadFile(file, uploadUrl, additionalData = {}) {
const formData = new FormData();
formData.append('file', file, file.name); // 'file' is the field name expected by the server
// Append any additional text data
for (const key in additionalData) {
formData.append(key, additionalData[key]);
}
try {
const response = await fetch(uploadUrl, {
method: 'POST',
body: formData, // FormData automatically sets the 'Content-Type': 'multipart/form-data' header
// You can also add other headers like Authorization if needed
// headers: {
// 'Authorization': 'Bearer YOUR_TOKEN'
// }
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('File upload successful:', result);
return result;
} catch (error) {
console.error('File upload failed:', error);
throw error;
}
}
// Example Usage (assuming you have an input type="file" element):
// const fileInput = document.getElementById('file-uploader');
// fileInput.addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// try {
// await uploadFile(selectedFile, 'https://api.example.com/upload', {
// description: 'User profile picture',
// userId: '123'
// });
// alert('File uploaded successfully!');
// } catch (error) {
// alert('File upload failed: ' + error.message);
// }
// }
// });
How it works: This snippet demonstrates how to upload a file to an API endpoint using JavaScript's `FormData` object. It creates a `FormData` instance, appends the selected file and any additional data, then sends it via a `POST` request using the `fetch` API. `FormData` handles setting the correct `Content-Type` header (`multipart/form-data`) automatically, simplifying file uploads.