JAVASCRIPT
Upload Files to a REST API with JavaScript FormData
Learn to effectively upload files (e.g., images, documents) to a backend API using `FormData` with the Fetch API, handling multipart/form-data requests.
async function uploadFile(fileInput, url) {
try {
const file = fileInput.files[0];
if (!file) {
throw new Error("No file selected.");
}
const formData = new FormData();
formData.append('file', file); // 'file' is the field name your backend expects
formData.append('fileName', file.name);
// Add other data if needed:
// formData.append('userId', '123');
const response = await fetch(url, {
method: 'POST',
// When using FormData, the 'Content-Type' header is automatically set
// to 'multipart/form-data' by the browser, including the boundary.
// DO NOT manually set it, or it will break the upload.
body: formData
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`HTTP error! Status: ${response.status}, Details: ${errorData.message || 'Unknown error'}`);
}
const uploadResult = await response.json();
return uploadResult;
} catch (error) {
console.error("Error uploading file:", error);
throw error;
}
}
// Example usage:
// First, ensure you have an HTML input type="file" element:
// <input type="file" id="fileUploadInput">
// <button onclick="handleFileUpload()">Upload</button>
/*
async function handleFileUpload() {
const fileInput = document.getElementById('fileUploadInput');
try {
const result = await uploadFile(fileInput, 'https://api.example.com/upload');
console.log('File uploaded successfully:', result);
alert('File uploaded!');
} catch (error) {
console.error('File upload failed:', error.message);
alert('File upload failed: ' + error.message);
}
}
*/
How it works: This snippet demonstrates how to upload files to a REST API endpoint using JavaScript's `FormData` object with the Fetch API. `FormData` allows you to construct a set of key/value pairs representing form fields and their values, including files. The browser automatically sets the correct `Content-Type: multipart/form-data` header when a `FormData` object is passed as the `body`, which is essential for file uploads. This ensures files are sent correctly for backend processing.