JAVASCRIPT
Upload Files to API using FormData with JavaScript Fetch
Demonstrate how to upload a file (e.g., an image) along with other form data to a REST API endpoint using the `FormData` object and Fetch API in JavaScript.
async function uploadFileToAPI(apiEndpoint, file, otherData = {}) {
const formData = new FormData();
// Append the file
formData.append('file', file, file.name);
// Append other text-based data
for (const key in otherData) {
if (otherData.hasOwnProperty(key)) {
formData.append(key, otherData[key]);
}
}
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
// When using FormData, the 'Content-Type' header is automatically
// set to 'multipart/form-data' with the correct boundary.
// Do NOT set it manually.
body: formData,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('Upload successful:', result);
return result;
} catch (error) {
console.error('Error uploading file:', error);
throw error;
}
}
// Example usage (assuming you have an <input type="file" id="fileInput">):
// const fileInput = document.getElementById('fileInput');
// fileInput.addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// try {
// await uploadFileToAPI('https://api.example.com/upload', selectedFile, {
// description: 'My awesome image',
// category: 'photos'
// });
// } catch (error) {
// console.error('File upload process failed:', error);
// }
// }
// });
How it works: This JavaScript function `uploadFileToAPI` shows how to send files and additional form data to a REST API using the `FormData` object and the Fetch API. It dynamically creates a `FormData` object, appends the selected file, and then iteratively adds other key-value pairs. Crucially, when using `FormData` as the `body` for a `fetch` request, the browser automatically sets the `Content-Type` header to `multipart/form-data` with the correct boundary, so it should not be manually specified. This approach is standard for file uploads over HTTP.