Uploading Files to an API using FormData
Owner: SnippetBot
Created: 2026-07-21 00:00:21
Size: 1.84 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
async function uploadFileToApi(apiUrl, file, metadata = {}) {
if (!file instanceof File) {
throw new Error('Provided item is not a File object.');
}
const formData = new FormData();
formData.append('file', file, file.name); // 'file' is the field name the API expects for the file
// Append any additional metadata
for (const key in metadata) {
if (Object.prototype.hasOwnProperty.call(metadata, key)) {
formData.append(key, metadata[key]);
}
}
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: formData,
// When using FormData, the 'Content-Type' header is automatically set
// to 'multipart/form-data' with the correct boundary. Do NOT set it manually.
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`File upload failed: ${response.status} ${response.statusText}. Details: ${errorText}`);
}
return await response.json();
} catch (error) {
console.error('Error during file upload:', error);
throw error;
}
}
// Example Usage (in a browser environment):
// const fileInput = document.querySelector('#fileInput');
// const uploadButton = document.querySelector('#uploadButton');
// uploadButton.addEventListener('click', async () => {
// if (fileInput.files.length > 0) {
// const selectedFile = fileInput.files[0];
// const additionalData = { userId: '123', category: 'documents' };
// try {
// const result = await uploadFileToApi('https://api.example.com/upload', selectedFile, additionalData);
// console.log('Upload successful:', result);
// alert('File uploaded successfully!');
// } catch (error) {
// console.error('Upload failed:', error);
// alert('File upload failed: ' + error.message);
// }
// } else {
// alert('Please select a file first.');
// }
// });