JAVASCRIPT

Uploading Multiple Files to an API with FormData

Discover how to efficiently upload multiple files to an API endpoint using JavaScript's FormData object, perfect for forms requiring several file attachments.

async function uploadMultipleFiles(files, endpointUrl, additionalData = {}) {
  const formData = new FormData();

  // Append files
  for (let i = 0; i < files.length; i++) {
    formData.append('files', files[i]); // 'files' is the expected field name by the server
  }

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

  try {
    const response = await fetch(endpointUrl, {
      method: 'POST',
      body: formData,
      // When using FormData, the 'Content-Type' header is usually set automatically
      // with the correct 'multipart/form-data' value, including the boundary.
      // Do NOT set it manually unless you know what you're doing, as it might break.
    });

    if (response.ok) {
      const result = await response.json();
      console.log('Files uploaded successfully:', result);
      return result;
    } else {
      const errorData = await response.json();
      console.error('Upload failed:', response.status, errorData);
      throw new Error(`Upload failed with status ${response.status}: ${errorData.message || JSON.stringify(errorData)}`);
    }
  } catch (error) {
    console.error('Network or server error during upload:', error);
    throw error;
  }
}

// Example Usage (assuming you have an input element <input type='file' multiple id='fileInput'>):
document.addEventListener('DOMContentLoaded', () => {
  const fileInput = document.getElementById('fileInput');
  const uploadButton = document.getElementById('uploadButton');

  if (uploadButton && fileInput) {
    uploadButton.addEventListener('click', async () => {
      if (fileInput.files.length > 0) {
        try {
          await uploadMultipleFiles(
            fileInput.files,
            'https://api.example.com/upload-multi',
            { userId: 'abc123', category: 'documents' }
          );
          alert('Files uploaded successfully!');
        } catch (error) {
          alert('Failed to upload files: ' + error.message);
        }
      } else {
        alert('Please select files to upload.');
      }
    });
  }
});
How it works: This snippet demonstrates how to upload multiple files to an API endpoint using the `FormData` object in JavaScript. It iterates through a `FileList` (from a multiple file input) and appends each file to the `FormData` object under a specified field name (e.g., 'files'). Additional data can also be appended. The `FormData` object is then used as the `body` of a `fetch` POST request. The browser automatically sets the correct `Content-Type` header (`multipart/form-data`), which is crucial for server-side processing of 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