Uploading Files to an API with FormData (Fetch API)
Owner: SnippetBot
Created: 2026-08-11 00:00:32
Size: 1.59 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
async function uploadFileToApi(apiUrl, file, additionalFields = {}) {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name expected by the server
// Append any additional text fields
for (const key in additionalFields) {
formData.append(key, additionalFields[key]);
}
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: formData // Fetch API automatically sets Content-Type to multipart/form-data with boundary
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`File upload failed: ${response.status} - ${errorData.message}`);
}
return await response.json();
} catch (error) {
console.error('Error uploading file:', error);
throw error;
}
}
// Example usage (assuming you have an <input type="file" id="fileInput"> in your HTML):
// const fileInput = document.getElementById('fileInput');
// if (fileInput) {
// fileInput.addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// const uploadUrl = 'https://api.example.com/upload'; // Your API endpoint
// const extraData = {
// description: 'An uploaded document',
// category: 'reports'
// };
// try {
// const result = await uploadFileToApi(uploadUrl, selectedFile, extraData);
// console.log('Upload successful:', result);
// } catch (error) {
// console.error('Upload failed:', error);
// }
// }
// });
// }