JAVASCRIPT
Uploading Files to a REST API with FormData and Fetch API
Learn how to upload files (e.g., images, documents) to a backend API using JavaScript's FormData object and the Fetch API, handling multipart/form-data.
async function uploadFileToAPI(url, file, additionalData = {}) {
const formData = new FormData();
formData.append('file', file); // 'file' is the name of the file input field on the server
// Append any additional data
for (const key in additionalData) {
formData.append(key, additionalData[key]);
}
try {
const response = await fetch(url, {
method: 'POST',
body: formData, // Fetch API automatically sets Content-Type to multipart/form-data
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || `HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('File Upload Error:', error);
throw error;
}
}
// Example Usage with a file input
/*
<input type="file" id="myFileInput" />
<button onclick="handleUpload()">Upload</button>
async function handleUpload() {
const fileInput = document.getElementById('myFileInput');
const file = fileInput.files[0];
if (!file) {
alert('Please select a file first.');
return;
}
try {
const result = await uploadFileToAPI('https://api.example.com/upload', file, { userId: '123' });
console.log('Upload successful:', result);
} catch (err) {
console.error('Upload failed:', err);
}
}
*/
How it works: This snippet demonstrates how to upload a file to a server using the `FormData` object and the `fetch` API. `FormData` is essential for sending `multipart/form-data` requests, which are commonly used for file uploads. The `fetch` API automatically sets the correct `Content-Type` header when `body` is a `FormData` object, simplifying the process.