JAVASCRIPT
Upload Files to API with FormData
Discover how to upload single or multiple files to a REST API endpoint using the FormData API in JavaScript, perfect for images, documents, or other binaries.
async function uploadFile(apiEndpoint, file, additionalData = {}) {
try {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name your API expects
// Append any additional text data if needed
for (const key in additionalData) {
formData.append(key, additionalData[key]);
}
const response = await fetch(apiEndpoint, {
method: 'POST',
body: formData // No need to set Content-Type header; FormData does it automatically
});
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('Error uploading file:', error);
throw error;
}
}
// Example usage (assuming an <input type="file" id="fileInput"> exists):
// document.getElementById('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', userId: '123' };
// try {
// await uploadFile(uploadUrl, selectedFile, metadata);
// } catch (error) {
// // Handle upload error in UI
// }
// }
// });
How it works: This snippet demonstrates how to upload files to an API using JavaScript's `FormData` interface. It creates a `FormData` object, appends the selected file (and optional additional data like a description or user ID) to it, and then sends it via a `POST` request using `fetch`. `FormData` automatically handles setting the correct `Content-Type` header (e.g., `multipart/form-data`), making file uploads straightforward without manual header configuration.