JAVASCRIPT

Uploading a File to an API using FormData

Learn to upload files to an API endpoint using JavaScript's FormData object and fetch API, correctly handling file and additional data submission.

async function uploadFileToAPI(file, extraData = {}) {
  const formData = new FormData();
  formData.append('file', file); // 'file' is the name of the expected field on the server

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

  try {
    const response = await fetch('https://api.example.com/upload', {
      method: 'POST',
      body: formData // No need to set 'Content-Type': 'multipart/form-data'; fetch handles it
    });

    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 an HTML input: <input type="file" id="fileInput">
// and a button: <button id="uploadButton">Upload</button>

// document.getElementById('uploadButton')?.addEventListener('click', async () => {
//   const fileInput = document.getElementById('fileInput');
//   const selectedFile = fileInput.files[0];

//   if (selectedFile) {
//     try {
//       const metadata = {
//         fileName: selectedFile.name,
//         fileSize: selectedFile.size,
//         description: 'User uploaded image'
//       };
//       await uploadFileToAPI(selectedFile, metadata);
//       alert('File uploaded successfully!');
//     } catch (error) {
//       alert('File upload failed!');
//     }
//   } else {
//     alert('Please select a file first.');
//   }
// });
How it works: This snippet demonstrates how to upload a file to an API endpoint using JavaScript's `FormData` object and the `fetch` API. `FormData` is essential for sending `multipart/form-data` requests, which are typically used for file uploads, allowing both binary file data and additional text fields to be sent in a single request. The code outlines how to construct the `FormData` object, append the file and any accompanying metadata, and handle the API response and potential errors.

Need help integrating this into your project?

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

Hire DigitalCodeLabs