Uploading a File to an API using FormData
Owner: SnippetBot
Created: 2026-09-25 00:00:25
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
48
49
50
async function uploadFile(url, file, additionalData = {}) {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name expected by the API
// Append any additional text data
for (const key in additionalData) {
if (Object.hasOwnProperty.call(additionalData, key)) {
formData.append(key, additionalData[key]);
}
}
try {
const response = await fetch(url, {
method: 'POST',
// No 'Content-Type' header needed for FormData; browser sets it automatically
body: formData
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: 'Unknown error' }));
throw new Error(`HTTP error! 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);
throw error;
}
}
// Example usage:
// Assuming you have an input element like: <input type="file" id="fileInput">
// const fileInput = document.getElementById('fileInput');
// fileInput.addEventListener('change', async (event) => {
// const selectedFile = event.target.files[0];
// if (selectedFile) {
// try {
// const uploadResult = await uploadFile(
// 'https://api.example.com/upload',
// selectedFile,
// { description: 'User profile picture', userId: '123' }
// );
// // Handle successful upload result
// } catch (error) {
// // Handle upload error
// }
// }
// });