JAVASCRIPT
Uploading Files to an API with Multipart Form Data in JavaScript
Learn how to correctly construct and send a `multipart/form-data` request with files and additional fields to an API using JavaScript's Fetch API.
async function uploadFile(file, additionalData = {}) {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name the API expects for the file
// Append any additional text data
for (const key in additionalData) {
if (additionalData.hasOwnProperty(key)) {
formData.append(key, additionalData[key]);
}
}
try {
const response = await fetch('https://api.example.com/upload', {
method: 'POST',
body: formData, // No Content-Type header needed; fetch sets it automatically for FormData
// You might need to add authorization headers
// headers: {
// 'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
// }
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`File upload failed: ${response.status} - ${JSON.stringify(errorData)}`);
}
const result = await response.json();
console.log('File uploaded successfully:', result);
return result;
} catch (error) {
console.error('Error during file upload:', error);
throw error;
}
}
// Example Usage:
// <input type="file" id="fileInput" />
// <button id="uploadButton">Upload File</button>
document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('fileInput');
const uploadButton = document.getElementById('uploadButton');
if (fileInput && uploadButton) {
uploadButton.addEventListener('click', async () => {
if (fileInput.files.length === 0) {
alert('Please select a file to upload.');
return;
}
const selectedFile = fileInput.files[0];
const additionalInfo = {
description: 'Uploaded from web client',
category: 'documents',
userId: 'user123'
};
try {
await uploadFile(selectedFile, additionalInfo);
alert('File upload process initiated. Check console for details.');
} catch (error) {
alert(`Upload failed: ${error.message}`);
}
});
} else {
console.warn('Elements with ID "fileInput" or "uploadButton" not found. File upload example won\'t run.');
}
// Manual test (requires a File object, e.g., from a data URL or mock)
// async function manualTest() {
// const mockFile = new File(["hello world"], "test.txt", { type: "text/plain" });
// const mockData = {
// client: "frontend-app",
// purpose: "manual-test"
// };
// try {
// await uploadFile(mockFile, mockData);
// } catch (e) {
// console.error("Manual upload test failed:", e);
// }
// }
// manualTest();
});
How it works: This JavaScript snippet demonstrates how to upload files to an API endpoint using `multipart/form-data`. It constructs a `FormData` object, appending the selected file along with any additional key-value text data required by the API (like a description or user ID). The `fetch` API is then used to send this `FormData` object, which automatically sets the correct `Content-Type: multipart/form-data` header. This is the standard and most robust method for sending files and mixed data to a server-side API, crucial for applications dealing with user-generated content, document uploads, or image processing.