JAVASCRIPT

Upload Files to an API with FormData

Efficiently upload files (images, documents) to a web API using JavaScript's FormData interface and the Fetch API, suitable for file submission forms.

async function uploadFile(endpoint, fileObject, additionalData = {}) {
  const formData = new FormData();
  formData.append('file', fileObject, fileObject.name); // 'file' is the field name expected by the server

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

  try {
    const response = await fetch(endpoint, {
      method: 'POST',
      // DO NOT set Content-Type header manually for FormData.
      // The browser will set it automatically, including the boundary.
      body: formData
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({ message: 'File upload failed.' }));
      throw new Error(`Upload Failed: ${response.status} - ${errorData.message || JSON.stringify(errorData)}`);
    }

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

// Usage example (requires a File object, typically from an <input type="file">)
// const fileInput = document.querySelector('#myFileInput'); // Assuming an HTML input
// if (fileInput && fileInput.files.length > 0) {
//   const selectedFile = fileInput.files[0];
//   const postMetadata = { description: 'User profile picture', category: 'profile' };
//
//   uploadFile('https://api.example.com/upload', selectedFile, postMetadata)
//     .then(response => console.log('Server response:', response))
//     .catch(err => console.error('Upload error:', err.message));
// } else {
//   console.log('No file selected.');
// }
How it works: This snippet demonstrates how to upload files to an API using the `FormData` interface and the Fetch API. `FormData` allows constructing a set of key/value pairs representing form fields, including files. It's crucial *not* to manually set the `Content-Type` header when using `FormData` with Fetch, as the browser automatically handles the `multipart/form-data` header with the correct boundary.

Need help integrating this into your project?

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

Hire DigitalCodeLabs