JAVASCRIPT
Handling File Uploads to a REST API with `FormData`
Implement robust file uploads to a REST API from the browser using JavaScript's `FormData` and the `fetch` API, supporting multiple files.
// HTML structure (for context, not part of the JS snippet itself)
/*
<input type="file" id="fileInput" multiple />
<button id="uploadButton">Upload Files</button>
<p id="uploadStatus"></p>
*/
async function uploadFilesToAPI(files, apiUrl) {
const formData = new FormData();
// Append each file to the FormData object
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i], files[i].name); // 'files' is the expected field name on the server
}
// Add other form data if needed
// formData.append('userId', '123');
// formData.append('description', 'User uploaded documents');
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: formData, // No 'Content-Type' header needed for FormData; fetch sets it automatically
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Upload failed! Status: ${response.status}, Message: ${errorText}`);
}
const result = await response.json();
console.log('Files uploaded successfully:', result);
return result;
} catch (error) {
console.error('Error during file upload:', error.message);
throw error; // Re-throw for calling context
}
}
// Example usage in a browser environment:
// document.addEventListener('DOMContentLoaded', () => {
// const fileInput = document.getElementById('fileInput');
// const uploadButton = document.getElementById('uploadButton');
// const uploadStatus = document.getElementById('uploadStatus');
// const API_UPLOAD_URL = 'https://api.example.com/upload'; // Replace with your actual API endpoint
// if (uploadButton && fileInput && uploadStatus) {
// uploadButton.addEventListener('click', async () => {
// const selectedFiles = fileInput.files;
// if (selectedFiles.length === 0) {
// uploadStatus.textContent = 'Please select files to upload.';
// return;
// }
// uploadStatus.textContent = 'Uploading...';
// try {
// const uploadResult = await uploadFilesToAPI(selectedFiles, API_UPLOAD_URL);
// uploadStatus.textContent = `Upload complete! Response: ${JSON.stringify(uploadResult)}`;
// } catch (error) {
// uploadStatus.textContent = `Upload failed: ${error.message}`;
// }
// });
// }
// });
How it works: This snippet demonstrates how to upload one or more files to a REST API from a web browser using JavaScript's `FormData` interface and the `fetch` API. It creates a `FormData` object, appends each selected file (and any other form fields) to it, and then sends this object as the `body` of a `POST` request. The `fetch` API automatically handles setting the correct `Content-Type` header (e.g., `multipart/form-data`). Robust error handling is included to manage network issues and API-specific error responses, making file uploads reliable.