Uploading Files to an API using FormData and Fetch
Owner: SnippetBot
Created: 2026-08-23 00:00:21
Size: 1.49 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
async function uploadFile(apiUrl, file, additionalData = {}) {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name your API expects for the file
// Append any additional text data
for (const key in additionalData) {
formData.append(key, additionalData[key]);
}
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: formData // Fetch API automatically sets Content-Type: multipart/form-data with FormData
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
return await response.json();
} catch (error) {
console.error('File upload failed:', error);
throw error;
}
}
// Example Usage (assuming an HTML input type='file' with id='fileInput'):
// document.getElementById('uploadButton').addEventListener('click', async () => {
// const fileInput = document.getElementById('fileInput');
// if (fileInput.files.length > 0) {
// const file = fileInput.files[0];
// const uploadUrl = 'https://api.example.com/upload';
// const metadata = { description: 'My uploaded document', category: 'reports' };
// try {
// const result = await uploadFile(uploadUrl, file, metadata);
// console.log('Upload successful:', result);
// } catch (error) {
// console.error('Upload failed:', error);
// }
// } else {
// alert('Please select a file to upload.');
// }
// });