JAVASCRIPT

Upload Files to a REST API Using FormData in JavaScript

Discover how to seamlessly upload files, including images or documents, to a RESTful API endpoint from your web application using JavaScript's FormData and fetch.

async function uploadFile(apiEndpoint, file, additionalData = {}) {
  const formData = new FormData();
  formData.append('file', file, file.name);

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

  try {
    const response = await fetch(apiEndpoint, {
      method: 'POST',
      body: formData // fetch automatically sets 'Content-Type': 'multipart/form-data' with FormData
    });

    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('File upload failed:', error);
    throw error;
  }
}

// Example usage with an HTML input type="file":
// const fileInput = document.getElementById('myFileInput');
// const uploadButton = document.getElementById('uploadButton');

// uploadButton.addEventListener('click', async () => {
//   if (fileInput.files.length > 0) {
//     const selectedFile = fileInput.files[0];
//     try {
//       const result = await uploadFile('https://api.example.com/upload', selectedFile, { description: 'User profile picture' });
//       console.log('Upload successful:', result);
//     } catch (error) {
//       console.error('Upload failed:', error.message);
//     }
//   } else {
//     alert('Please select a file to upload.');
//   }
// });

// To simulate file for testing (e.g., in Node.js or a test environment):
// const dummyFile = new File(['hello world'], 'hello.txt', { type: 'text/plain' });
// uploadFile('https://api.example.com/upload', dummyFile, { userId: 123 })
//   .then(res => console.log('Dummy upload success:', res))
//   .catch(err => console.error('Dummy upload error:', err));
How it works: This JavaScript snippet demonstrates how to upload files to a REST API endpoint using the `FormData` interface and the `fetch` API. `FormData` allows you to construct a set of key/value pairs representing form fields and their values, including file content. When passed as the `body` of a `fetch` request, it automatically sets the correct `Content-Type: multipart/form-data` header, making file uploads straightforward and efficient from the browser or Node.js environments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs