JAVASCRIPT
Upload Files to an API using FormData
Efficiently upload files, along with additional data, to a backend API using JavaScript's FormData and the Fetch API, perfect for forms with file inputs.
async function uploadFileToAPI(file, metadata = {}) {
const apiUrl = 'https://api.example.com/upload';
const formData = new FormData();
// Append the file
formData.append('file', file, file.name); // 'file' is the field name expected by the API
// Append additional metadata
for (const key in metadata) {
if (Object.hasOwnProperty.call(metadata, key)) {
formData.append(key, metadata[key]);
}
}
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: formData, // Fetch API automatically sets Content-Type: multipart/form-data with boundary
// You might need to include Authorization headers if your API requires it
// headers: {
// 'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
// }
});
if (!response.ok) {
const errorData = await response.json().catch(() => response.text());
throw new Error(`Upload failed with status ${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 (assuming you have an <input type="file" id="fileInput"> element)
// document.getElementById('fileInput').addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// const additionalData = {
// description: 'A photo of my cat',
// userId: '123'
// };
// try {
// const uploadResult = await uploadFileToAPI(selectedFile, additionalData);
// alert('Upload complete! Check console for details.');
// } catch (error) {
// alert('Upload failed: ' + error.message);
// }
// }
// });
How it works: This JavaScript snippet demonstrates how to upload files to an API using `FormData` and the `fetch` API. It creates a `FormData` object, appends the selected file from an input field, and includes any additional data as key-value pairs. When `fetch` is called with the `FormData` object as the `body`, it automatically sets the correct `Content-Type: multipart/form-data` header, streamlining the process of sending binary file data along with other form fields to a backend API.