JAVASCRIPT
Securely Uploading Files to an API with FormData
Learn to upload files, images, or documents to a server-side API using JavaScript's FormData object, supporting both single and multiple file uploads in web applications.
async function uploadFiles(apiUrl, files, additionalData = {}) {
const formData = new FormData();
// Append files (can be single or array of File objects)
if (Array.isArray(files)) {
files.forEach((file, index) => {
formData.append(`file${index}`, file); // Use unique keys for multiple files
});
} else {
formData.append('file', files); // Single file
}
// Append any additional text data
for (const key in additionalData) {
if (Object.prototype.hasOwnProperty.call(additionalData, key)) {
formData.append(key, additionalData[key]);
}
}
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: formData, // fetch API automatically sets 'Content-Type': 'multipart/form-data'
// headers: { 'Authorization': 'Bearer YOUR_TOKEN' } // Add auth if needed
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Upload failed: ${response.status} - ${errorText}`);
}
return await response.json(); // Or response.text() depending on API
} catch (error) {
console.error('File upload error:', error);
throw error;
}
}
// Example Usage:
// const inputElement = document.querySelector('input[type="file"]');
// inputElement.addEventListener('change', async (event) => {
// const selectedFiles = event.target.files; // FileList object
// if (selectedFiles.length > 0) {
// try {
// const result = await uploadFiles('https://api.example.com/upload', selectedFiles, { description: 'User photo' });
// console.log('Upload successful:', result);
// } catch (error) {
// console.error('Upload failed:', error.message);
// }
// }
// });
How it works: This snippet demonstrates how to upload one or more files to an API endpoint using JavaScript's `FormData` object. It constructs a `FormData` instance, appends the file(s) and any additional text data, then sends it via a `POST` request using the `fetch` API. `FormData` correctly sets the `Content-Type` header to `multipart/form-data`, which is necessary for file uploads.