JAVASCRIPT

Securely Uploading Files to an API with FormData (JavaScript Frontend)

Learn how to use JavaScript `FormData` to construct and send multipart/form-data requests, securely uploading files and additional data to an API.

async function uploadFileToAPI(apiEndpoint, fileInputId, additionalData = {}) {
    const fileInput = document.getElementById(fileInputId);
    if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
        console.error('No file selected for upload.');
        alert('Please select a file to upload.');
        return;
    }

    const file = fileInput.files[0];
    const formData = new FormData();

    // Append the file
    formData.append('file', file, file.name);

    // Append additional data
    for (const key in additionalData) {
        formData.append(key, additionalData[key]);
    }

    try {
        const response = await fetch(apiEndpoint, {
            method: 'POST',
            body: formData,
            // When using FormData, the 'Content-Type' header is automatically set to 'multipart/form-data'
            // with the correct boundary. Manually setting it often causes issues.
            // headers: {
            //     'Authorization': 'Bearer YOUR_AUTH_TOKEN_HERE', // Add if your API requires authentication
            // }
        });

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

        const result = await response.json();
        console.log('Upload successful:', result);
        alert('File uploaded successfully!');
        return result;
    } catch (error) {
        console.error('Error during file upload:', error.message);
        alert(`File upload failed: ${error.message}`);
        throw error;
    }
}

// Example HTML (assuming this snippet is in a script tag):
/*
<input type="file" id="myFileInput" />
<button onclick="uploadFileToAPI('/api/upload', 'myFileInput', { userId: '123', category: 'documents' })">Upload</button>
*/
How it works: This JavaScript function facilitates uploading files and associated data to an API using `FormData`. It takes a file from an `<input type="file">` element and any extra key-value pairs, then constructs a `FormData` object. This object is sent as the `body` of a `POST` request using the `fetch` API. `FormData` correctly handles the `multipart/form-data` encoding, which is essential for file uploads.

Need help integrating this into your project?

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

Hire DigitalCodeLabs