JAVASCRIPT

Upload Files to an API via Multipart/form-data in JavaScript

Learn to send files to a REST API endpoint using `FormData` and `fetch` in JavaScript, demonstrating secure and efficient multipart/form-data uploads.

async function uploadFileToApi(file, endpointUrl, additionalData = {}) {
    const formData = new FormData();
    
    // Append the file
    formData.append('file', file, file.name); // 'file' is the field name expected by the API
    
    // Append any additional data
    for (const key in additionalData) {
        formData.append(key, additionalData[key]);
    }

    try {
        const response = await fetch(endpointUrl, {
            method: 'POST',
            body: formData,
            // Do NOT manually set 'Content-Type' header when using FormData with fetch.
            // Fetch will automatically set it to 'multipart/form-data' with the correct boundary.
            // headers: {
            //     'Authorization': 'Bearer YOUR_AUTH_TOKEN' // Example for authenticated requests
            // }
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
        }

        return await response.json(); // Assuming the API returns JSON
    } catch (error) {
        console.error('Error uploading file:', error);
        throw error;
    }
}

// Example Usage (e.g., in a browser context with an <input type="file">)
/*
document.getElementById('fileInput').addEventListener('change', async (event) => {
    const selectedFile = event.target.files[0];
    if (selectedFile) {
        try {
            const result = await uploadFileToApi(
                selectedFile,
                'https://api.example.com/upload',
                { description: 'A user-uploaded image' }
            );
            console.log('File upload successful:', result);
            alert('File uploaded successfully!');
        } catch (error) {
            console.error('Upload failed:', error.message);
            alert('File upload failed!');
        }
    }
});
*/
How it works: This JavaScript function `uploadFileToApi` demonstrates how to send a file to a REST API using `FormData` and the browser's `fetch` API. It creates a `FormData` object, appends the file (and any optional additional data), and then sends it as a `POST` request. The `fetch` API automatically handles setting the correct `Content-Type: multipart/form-data` header, making file uploads straightforward and efficient for various API integrations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs