JAVASCRIPT

Upload Files to an API Using FormData in JavaScript

Master file uploads to REST APIs using JavaScript's FormData object with the Fetch API, perfect for sending images, documents, and other binary data.

async function uploadFileToAPI(file, otherData) {
  const formData = new FormData();
  formData.append('file', file); // 'file' is the field name the API expects

  // Append other text-based data if needed
  for (const key in otherData) {
    formData.append(key, otherData[key]);
  }

  try {
    const response = await fetch('https://api.example.com/upload', {
      method: 'POST',
      // When using FormData, the 'Content-Type' header is automatically set to 'multipart/form-data'
      // with the correct 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('Upload successful:', result);
    return result;
  } catch (error) {
    console.error('Error uploading file:', error);
    throw error;
  }
}

// Example Usage (e.g., triggered by an input type='file' change event):
// const fileInput = document.getElementById('myFileInput');
// fileInput.addEventListener('change', async (event) => {
//   const selectedFile = event.target.files[0];
//   if (selectedFile) {
//     try {
//       const additionalInfo = { description: 'User profile picture', category: 'images' };
//       await uploadFileToAPI(selectedFile, additionalInfo);
//     } catch (error) {
//       alert('File upload failed!');
//     }
//   }
// });
How it works: This JavaScript snippet demonstrates how to upload files to a REST API using the `FormData` object and the `fetch` API. `FormData` is crucial for sending data in `multipart/form-data` format, which is typically required for file uploads. The snippet shows how to append the file itself, along with any other accompanying text data, to the `FormData` object. The `fetch` API then sends this `FormData` in a POST request, automatically handling the `Content-Type` header, simplifying the process of interacting with file upload endpoints.

Need help integrating this into your project?

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

Hire DigitalCodeLabs