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