JAVASCRIPT
Uploading Files to a REST API using FormData
Learn how to correctly send files to a REST API endpoint using JavaScript's `FormData` object and `fetch` for multipart/form-data requests.
async function uploadFileToApi(endpoint, file, additionalData = {}) {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name the API expects
// Append any additional text data
for (const key in additionalData) {
formData.append(key, additionalData[key]);
}
try {
const response = await fetch(endpoint, {
method: 'POST',
body: formData, // fetch automatically sets 'Content-Type': 'multipart/form-data' with boundary
// Add custom headers if needed, e.g., 'Authorization': 'Bearer YOUR_TOKEN'
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`File upload failed: ${response.status} ${response.statusText} - ${errorText}`);
}
return await response.json(); // Assuming API returns JSON
} catch (error) {
console.error('Error during file upload:', error);
throw error;
}
}
// Example usage with an HTML file input:
/*
document.getElementById('uploadForm').addEventListener('submit', async (event) => {
event.preventDefault();
const fileInput = document.getElementById('myFile');
const file = fileInput.files[0];
if (!file) {
alert('Please select a file.');
return;
}
const userId = 'user123';
try {
const result = await uploadFileToApi('https://api.example.com/upload', file, { userId: userId, category: 'documents' });
console.log('Upload successful:', result);
alert('File uploaded successfully!');
} catch (error) {
console.error('Upload failed:', error);
alert('File upload failed. Check console for details.');
}
});
// HTML structure for example:
// <form id="uploadForm">
// <input type="file" id="myFile" />
// <button type="submit">Upload</button>
// </form>
*/
How it works: This JavaScript snippet shows how to upload files to a REST API using `FormData`. The `FormData` object constructs a set of key/value pairs representing form fields, including files, which are then sent as a `multipart/form-data` request. The `fetch` API automatically handles setting the correct `Content-Type` header when a `FormData` object is provided as the body, simplifying file uploads.