← Back to all snippets
JAVASCRIPT

Uploading Files to an API with JavaScript FormData

Learn how to programmatically upload files to a backend API using JavaScript's `FormData` object, suitable for forms with file inputs.

async function uploadFileToAPI(url, file, additionalData = {}) {
  const formData = new FormData();
  formData.append('file', file); // 'file' is the field name expected by the backend

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

  try {
    const response = await fetch(url, {
      method: 'POST',
      body: formData, // fetch automatically sets Content-Type: multipart/form-data
      // headers: { 'Authorization': 'Bearer YOUR_TOKEN' } // Include if authentication is needed
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`HTTP error! status: ${response.status}. Message: ${errorText}`);
    }

    return await response.json();

  } 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 uploadFileToAPI(
        'https://api.example.com/upload',
        selectedFile,
        { description: 'User profile picture', userId: '123' }
      );
      console.log('File uploaded successfully:', uploadResult);
    } catch (error) {
      console.error('File upload failed:', error);
    }
  }
});
*/

// Alternative example for creating a dummy File object for testing:
// const dummyFile = new File(['hello world'], 'hello.txt', { type: 'text/plain' });
// uploadFileToAPI('https://api.example.com/upload', dummyFile)
//  .then(res => console.log(res))
//  .catch(err => console.error(err));
How it works: This JavaScript function demonstrates how to upload files to an API using the `FormData` object. It appends the selected file and any additional text-based data to `FormData`, which is then sent as the request body in a POST request. The `fetch` API automatically handles setting the correct `Content-Type: multipart/form-data` header. This method is essential for handling file uploads in web applications, often used for user avatars, document uploads, or image galleries.

Need help integrating this into your project?

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

Hire DigitalCodeLabs