JAVASCRIPT

Uploading Files to an API using FormData in JavaScript

Discover how to programmatically send file uploads along with other form data to a REST API using JavaScript's `FormData` object with the `fetch` API.

async function uploadFile(apiUrl, file, additionalData = {}) {
  const formData = new FormData();
  formData.append('file', file); // 'file' is the field name the API expects

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

  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      // When using FormData, Content-Type header is automatically set to multipart/form-data
      // and includes the boundary, so do NOT set it manually.
      body: formData
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

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

// Example Usage (assuming you have a file input element):
// const fileInput = document.querySelector('#myFileInput');
// fileInput.addEventListener('change', async (event) => {
//   const selectedFile = event.target.files[0];
//   if (selectedFile) {
//     try {
//       const uploadResult = await uploadFile('https://api.example.com/upload', selectedFile, {
//         description: 'My awesome document',
//         category: 'reports'
//       });
//       console.log('Upload completed:', uploadResult);
//     } catch (error) {
//       console.error('Upload failed:', error);
//     }
//   }
// });
How it works: This snippet shows how to upload files to an API using JavaScript's `FormData` object. It allows sending one or more files along with other textual data in a single request, mimicking an HTML form submission. The `FormData` object correctly handles the `multipart/form-data` encoding, removing the need to manually set the `Content-Type` header when using `fetch`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs