JAVASCRIPT

JavaScript File Upload with FormData

Implement client-side file uploads in JavaScript using FormData to send files and other form data to a REST API endpoint, covering both single and multiple file scenarios.

async function uploadFile(fileInputId, apiUrl, additionalData = {}) {
    const fileInput = document.getElementById(fileInputId);
    if (!fileInput || !fileInput.files.length) {
        console.warn('No files selected for upload.');
        return;
    }

    const formData = new FormData();

    // Append files (supports multiple files if input allows)
    for (const file of fileInput.files) {
        formData.append('files', file); // 'files' is the field name expected by the server
    }

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

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            body: formData, // No 'Content-Type' header needed for FormData; fetch sets it automatically
            // headers: {
            //     'Authorization': 'Bearer YOUR_AUTH_TOKEN'
            // }
        });

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

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

// Example HTML setup:
/*
<input type="file" id="myFileInput" multiple>
<button onclick="
    uploadFile('myFileInput', 'https://api.example.com/upload', {
        description: 'User uploaded image',
        userId: '123'
    })
    .then(res => console.log('File uploaded successfully!', res))
    .catch(err => console.error('Upload error:', err));
">Upload Files</button>
*/
How it works: This JavaScript snippet provides a client-side solution for uploading files to a REST API. It utilizes `FormData` to construct a multipart/form-data request, which is essential for sending binary data like files, alongside any additional text-based form fields. The `fetch` API is used to send this data, with error handling for network issues and server responses, making it a robust method for integrating file uploads into web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs