JAVASCRIPT

Upload Files to API Endpoints with FormData

Efficiently upload single or multiple files to an API endpoint using JavaScript's FormData, handling both text and binary data submissions.

async function uploadFileToAPI(endpoint, file, additionalData = {}) {
    try {
        const formData = new FormData();
        formData.append('file', file); // 'file' is the field name expected by the server

        // Append any additional text data
        for (const key in additionalData) {
            if (Object.prototype.hasOwnProperty.call(additionalData, key)) {
                formData.append(key, additionalData[key]);
            }
        }

        const response = await fetch(endpoint, {
            method: 'POST',
            body: formData // No Content-Type header needed for FormData; browser sets it with boundary
        });

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: response.statusText }));
            throw new Error(`API Error: ${response.status} - ${errorData.message}`);
        }

        const result = await response.json();
        console.log('File upload successful:', result);
        return result;
    } catch (error) {
        console.error('Error uploading file:', error);
        throw error;
    }
}

// Example Usage (requires an input type="file" element in HTML):
// const fileInput = document.querySelector('#myFileInput'); // Assuming you have <input type="file" id="myFileInput">
// if (fileInput) {
//     fileInput.addEventListener('change', async (event) => {
//         const selectedFile = event.target.files[0];
//         if (selectedFile) {
//             try {
//                 const uploadResult = await uploadFileToAPI(
//                     'https://api.example.com/upload',
//                     selectedFile,
//                     { userId: '123', description: 'User profile picture' }
//                 );
//                 alert('Upload complete! See console for details.');
//             } catch (err) {
//                 alert('Upload failed: ' + err.message);
//             }
//         }
//     });
// }
How it works: This JavaScript snippet demonstrates how to upload a file to an API endpoint using the `FormData` interface. `FormData` provides a way to construct a set of key/value pairs representing form fields and their values, including files. It's particularly useful for sending multipart/form-data requests, which are commonly used for file uploads. The browser automatically sets the correct `Content-Type` header (e.g., `multipart/form-data`) including the necessary boundary when you pass a `FormData` object as the `body` of a `fetch` request, simplifying the process for developers. You can also append additional text data alongside the file.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs