JAVASCRIPT
Uploading Files with Additional Data to an API using FormData
Learn how to send files along with structured data (e.g., text, JSON) to an API using JavaScript's FormData and Fetch API, enabling robust file uploads.
async function uploadFileWithMetadata(file, title, description, tags) {
const formData = new FormData();
// Append the file
formData.append('file', file, file.name);
// Append additional metadata fields
formData.append('title', title);
formData.append('description', description);
formData.append('tags', JSON.stringify(tags)); // Arrays or objects should be stringified
try {
const response = await fetch('https://api.example.com/upload', {
method: 'POST',
// No 'Content-Type' header needed for FormData; browser sets 'multipart/form-data' automatically
body: formData,
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Upload failed: ${response.status} - ${errorData.message || 'Unknown error'}`);
}
const result = await response.json();
console.log('Upload successful:', result);
return result;
} catch (error) {
console.error('Error during file upload:', error.message);
throw error;
}
}
// Example usage (e.g., from an input type='file' change event):
// const fileInput = document.querySelector('#fileInput');
// fileInput.addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// try {
// await uploadFileWithMetadata(selectedFile, 'My Awesome Photo', 'A beautiful landscape', ['nature', 'travel']);
// alert('File uploaded successfully!');
// } catch (error) {
// alert(`File upload failed: ${error.message}`);
// }
// }
// });
How it works: This JavaScript snippet demonstrates how to upload a file along with other form data (metadata) to an API endpoint using the `FormData` object and the `fetch` API. `FormData` is essential for constructing `multipart/form-data` requests, which are standard for file uploads. You append the file itself, and then other key-value pairs representing additional data. The browser automatically sets the correct `Content-Type` header, so it's not explicitly set in the `fetch` options. This is a robust way to handle file submissions in modern web applications.