JAVASCRIPT
Uploading Files to a REST API using JavaScript FormData
Learn to securely upload files to a REST API endpoint from a web frontend using JavaScript's FormData object and the Fetch API, handling various file types.
async function uploadFile(url, file, additionalData = {}) {
const formData = new FormData();
formData.append('file', file); // 'file' is the name of the input field on the server-side
// Append any additional data (e.g., user ID, description)
for (const key in additionalData) {
formData.append(key, additionalData[key]);
}
try {
const response = await fetch(url, {
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) {
const errorText = await response.text(); // or .json() if server sends JSON error
throw new Error(`HTTP error! Status: ${response.status}. Details: ${errorText}`);
}
const responseData = await response.json(); // Assuming server responds with JSON
console.log('File upload successful:', responseData);
return responseData;
} catch (error) {
console.error('Error during file upload:', error);
throw error;
}
}
// Example Usage (requires an actual file input element):
/*
// HTML: <input type="file" id="myFileInput"> <button id="uploadButton">Upload</button>
// document.getElementById('uploadButton').addEventListener('click', async () => {
// const fileInput = document.getElementById('myFileInput');
// if (fileInput.files.length > 0) {
// const selectedFile = fileInput.files[0];
// const userData = { userId: 123, description: 'User profile picture' };
// try {
// const result = await uploadFile('/api/upload', selectedFile, userData);
// alert('Upload success!');
// } catch (error) {
// alert('Upload failed: ' + error.message);
// }
// } else {
// alert('Please select a file first.');
// }
// });
*/
How it works: This JavaScript snippet provides a robust way to upload files to a REST API. It leverages the `FormData` object, which is essential for constructing `multipart/form-data` requests that APIs typically expect for file uploads. The file and any additional data are appended to the `FormData` object. The Fetch API then sends this `FormData` in a POST request. Importantly, the `Content-Type` header is automatically handled by the browser when using `FormData` directly as the `body`.