JAVASCRIPT
Upload Files to an API Using JavaScript FormData
Discover how to programmatically upload files to a backend API endpoint using JavaScript's FormData object, perfect for forms that include file inputs.
async function uploadFile(file, uploadUrl, token = null) {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name your API expects
formData.append('description', 'A file uploaded via JavaScript'); // Add other fields if needed
const headers = {};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
try {
const response = await fetch(uploadUrl, {
method: 'POST',
headers: headers,
body: formData
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Upload failed! Status: ${response.status}, Message: ${errorData.message || response.statusText}`);
}
const result = await response.json();
console.log('File uploaded successfully:', result);
return result;
} catch (error) {
console.error('Error uploading file:', error.message);
throw error;
}
}
// Example usage:
// Assume 'fileInput' is an HTML <input type="file"> element
// const fileInput = document.getElementById('fileInput');
// const selectedFile = fileInput.files[0];
// if (selectedFile) {
// const UPLOAD_URL = 'https://api.example.com/upload';
// const AUTH_TOKEN = 'your_auth_token'; // Optional
// uploadFile(selectedFile, UPLOAD_URL, AUTH_TOKEN)
// .then(data => console.log('Upload response:', data))
// .catch(err => console.error('Upload error:', err.message));
// } else {
// console.log('No file selected.');
// }
How it works: This code snippet shows how to upload a file to an API using JavaScript's `FormData` object. `FormData` allows you to construct a set of key/value pairs representing form fields, including files, which can then be sent via `fetch`.
Key steps include:
1. Creating a `FormData` instance.
2. Appending the file and any additional data using `formData.append()`.
3. Making a POST request with the `FormData` instance as the `body`. The `Content-Type` header is automatically set to `multipart/form-data` by the browser when a `FormData` object is passed as the body, so it's not explicitly set here.
4. Handling potential authentication with an optional token and comprehensive error management for the upload process.