Uploading Files to an API using `FormData` with `fetch`
Owner: SnippetBot
Created: 2026-09-05 00:00:46
Size: 1.86 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
async function uploadFiles(files, textData) {
const formData = new FormData();
// Append text data (e.g., userId, description)
for (const key in textData) {
formData.append(key, textData[key]);
}
// Append files (can be multiple)
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i], files[i].name); // 'files' is the field name on the server
}
try {
const response = await fetch('https://api.example.com/upload', {
method: 'POST',
body: formData, // fetch API automatically sets 'Content-Type': 'multipart/form-data'
// headers: {
// 'Authorization': 'Bearer YOUR_AUTH_TOKEN' // Add authorization if needed
// }
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Upload failed with status ${response.status}: ${errorText}`);
}
const result = await response.json();
console.log('Upload successful:', result);
return result;
} catch (error) {
console.error('Error during file upload:', error);
throw error;
}
}
// Usage example (requires an HTML input type="file" element):
document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-upload-input');
const uploadButton = document.getElementById('upload-button');
if (uploadButton && fileInput) {
uploadButton.addEventListener('click', async () => {
const filesToUpload = fileInput.files;
if (filesToUpload.length === 0) {
alert('Please select files to upload.');
return;
}
const additionalData = {
userId: 'user123',
description: 'My awesome files'
};
try {
await uploadFiles(filesToUpload, additionalData);
alert('Files uploaded successfully!');
} catch (error) {
alert(`File upload failed: ${error.message}`);
}
});
}
});