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 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); // } // } // }); // }