JAVASCRIPT
Uploading Files to a REST API with FormData
Learn how to securely upload files to a REST API using JavaScript's FormData, enabling robust handling of image, document, and other file types.
async function uploadFileToAPI(apiEndpoint, file, additionalData = {}) {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name expected by the API
// Append any additional text data
for (const key in additionalData) {
formData.append(key, additionalData[key]);
}
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
body: formData, // FormData automatically sets 'Content-Type': 'multipart/form-data'
// headers: {
// 'Authorization': 'Bearer YOUR_TOKEN_HERE', // Add authentication if needed
// }
});
if (!response.ok) {
const errorData = await response.json(); // Assuming API returns JSON error
throw new Error(`HTTP error! status: ${response.status} - ${errorData.message || response.statusText}`);
}
return await response.json();
} catch (error) {
console.error("Error uploading file:", error);
throw error;
}
}
// Example usage (assuming an HTML input type="file" element with id="fileInput"):
// const fileInput = document.getElementById('fileInput');
// fileInput.addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// try {
// const uploadResult = await uploadFileToAPI('https://api.example.com/upload', selectedFile, {
// description: 'My uploaded document',
// category: 'documents'
// });
// console.log('File uploaded successfully:', uploadResult);
// } catch (error) {
// console.error('File upload failed:', error);
// }
// }
// });
How it works: This JavaScript snippet demonstrates how to upload a file to a REST API using the `FormData` interface. It creates a `FormData` object, appends the selected file under a specified field name (e.g., 'file'), and can also include additional text data. The `fetch` API is then used with a `POST` method, allowing the browser to automatically set the correct `Content-Type: multipart/form-data` header for the request, simplifying file transmission.