JAVASCRIPT
Uploading Files to an API using FormData
Learn to securely upload files like images or documents to a REST API endpoint using JavaScript's fetch API and the FormData object for multipart/form-data.
async function uploadFile(url, file, token) {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name expected by the server
formData.append('description', 'User uploaded image'); // Add other fields if needed
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
// Do NOT set Content-Type header; FormData does it automatically
},
body: formData
});
if (!response.ok) {
const errorBody = await response.json();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorBody.message || 'Unknown error'}`);
}
const responseData = await response.json();
console.log('File upload successful:', responseData);
return responseData;
} catch (error) {
console.error('Error uploading file:', error);
throw error;
}
}
// Usage example with a file input:
// const fileInput = document.querySelector('#fileInput');
// fileInput.addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// const userToken = 'your_jwt_token_here';
// try {
// await uploadFile('https://api.example.com/upload', selectedFile, userToken);
// } catch (error) {
// console.error('Upload failed:', error);
// }
// }
// });
How it works: This snippet demonstrates how to upload files to an API endpoint. Instead of a JSON body, it uses `FormData` which is specifically designed for sending data in the `multipart/form-data` format, commonly used for file uploads. It's important to *not* manually set the `Content-Type` header when using `FormData`, as the browser handles it automatically, including the boundary string. Authentication with a Bearer token is also included.