JAVASCRIPT

Direct Client-Side File Upload using FormData and Fetch

Enable direct file uploads from your browser to external APIs using JavaScript's FormData and Fetch API, bypassing your backend for efficiency.

document.addEventListener('DOMContentLoaded', () => {
    const uploadForm = document.getElementById('fileUploadForm');
    const fileInput = document.getElementById('fileInput');
    const uploadStatus = document.getElementById('uploadStatus');

    if (!uploadForm || !fileInput || !uploadStatus) {
        console.error('Required DOM elements not found.');
        return;
    }

    uploadForm.addEventListener('submit', async (event) => {
        event.preventDefault(); // Prevent default form submission

        const file = fileInput.files[0];
        if (!file) {
            uploadStatus.textContent = 'Please select a file to upload.';
            uploadStatus.style.color = 'orange';
            return;
        }

        uploadStatus.textContent = 'Uploading...';
        uploadStatus.style.color = 'blue';

        // Replace with your actual third-party API upload endpoint
        const API_UPLOAD_URL = 'https://api.example.com/upload';
        // Important: Some APIs might require an API key or authentication header
        const API_KEY = 'your_third_party_api_key'; // Use securely, don't hardcode in production!

        const formData = new FormData();
        formData.append('file', file); // 'file' is often the expected field name by the API
        formData.append('fileName', file.name); // Optional: add other metadata

        try {
            const response = await fetch(API_UPLOAD_URL, {
                method: 'POST',
                headers: {
                    // 'Content-Type': 'multipart/form-data' is usually set automatically by browser
                    // when sending FormData, do NOT set it manually as it might break boundary.
                    // Add other required headers, e.g., for authentication
                    'Authorization': `Bearer ${API_KEY}`,
                    // 'X-API-Key': API_KEY,
                },
                body: formData,
            });

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

            const result = await response.json();
            uploadStatus.textContent = `Upload successful! Response: ${JSON.stringify(result)}`;
            uploadStatus.style.color = 'green';
            console.log('Upload result:', result);

        } catch (error)
        {
            uploadStatus.textContent = `Upload error: ${error.message}`;
            uploadStatus.style.color = 'red';
            console.error('File upload error:', error);
        }
    });
});
/*
<form id="fileUploadForm">
    <input type="file" id="fileInput" accept="image/*" />
    <button type="submit">Upload File</button>
</form>
<p id="uploadStatus"></p>
*/
How it works: This JavaScript snippet demonstrates how to perform a direct client-side file upload to a third-party API using `FormData` and the `fetch` API. It captures a selected file from an input element, constructs a `FormData` object with the file and optional metadata, and then sends it as a POST request. This approach is efficient as it can offload file handling from your backend, sending files directly to a dedicated storage or processing service.

Need help integrating this into your project?

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

Hire DigitalCodeLabs