JAVASCRIPT
Upload Files to API using JavaScript FormData
Efficiently send files, images, or other binary data to a backend API from the browser using the `FormData` object with standard `fetch` or `axios`.
/**
* Uploads a file (or files) and additional form data to an API endpoint.
* @param {string} url - The API endpoint URL for file upload.
* @param {File | File[]} files - The File object(s) to upload.
* @param {object} [additionalData={}] - Optional key-value pairs for additional form fields.
* @returns {Promise<Response>} The fetch response from the upload.
* @throws {Error} If the upload fails.
*/
async function uploadFilesToApi(url, files, additionalData = {}) {
const formData = new FormData();
// Append files
if (Array.isArray(files)) {
files.forEach((file, index) => {
formData.append(`file${index}`, file, file.name); // Use a distinct name for each file
});
} else {
formData.append('file', files, files.name); // Single file, use 'file' as the field name
}
// Append additional data
for (const key in additionalData) {
if (Object.prototype.hasOwnProperty.call(additionalData, key)) {
formData.append(key, additionalData[key]);
}
}
try {
const response = await fetch(url, {
method: 'POST',
// No need to set Content-Type header; FormData does it automatically
// and includes the correct boundary.
body: formData
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`File upload failed: ${response.status} - ${errorText}`);
}
return response;
} catch (error) {
console.error('Upload error:', error);
throw error;
}
}
// Example usage (assuming an input type="file" element in HTML):
// document.getElementById('uploadForm').addEventListener('submit', async (event) => {
// event.preventDefault();
// const fileInput = document.getElementById('fileInput');
// const descriptionInput = document.getElementById('description');
// if (fileInput.files.length > 0) {
// try {
// const response = await uploadFilesToApi(
// '/api/upload',
// fileInput.files[0], // Or Array.from(fileInput.files) for multiple
// { description: descriptionInput.value, userId: '123' }
// );
// const result = await response.json();
// console.log('Upload successful:', result);
// alert('File uploaded successfully!');
// } catch (error) {
// console.error('Error during upload:', error.message);
// alert('File upload failed!');
// }
// } else {
// alert('Please select a file to upload.');
// }
// });
How it works: This JavaScript snippet demonstrates how to upload files to an API using the `FormData` object, a standard web API for constructing form data for HTTP requests. It allows combining one or more `File` objects from an input field with additional text or binary data. The `FormData` object automatically handles setting the correct `Content-Type` header (e.g., `multipart/form-data`) and boundaries, simplifying the process of sending complex payloads to a backend endpoint designed to receive file uploads.