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