JAVASCRIPT

Upload Files and Data to an API using `multipart/form-data` in JavaScript

Explore how to correctly construct and send `multipart/form-data` requests with files and additional form fields to a backend API using JavaScript's Fetch API.

// Assume you have an HTML form like this:
/*
<form id="uploadForm">
  <input type="text" id="itemName" name="itemName" value="My Awesome Item">
  <input type="number" id="itemPrice" name="itemPrice" value="99.99">
  <input type="file" id="itemImage" name="itemImage" accept="image/*">
  <button type="submit">Upload Item</button>
</form>
*/

const uploadForm = document.getElementById('uploadForm');
const API_UPLOAD_URL = 'https://api.your-service.com/items/upload'; // Replace with your API endpoint

uploadForm.addEventListener('submit', async (event) => {
  event.preventDefault(); // Prevent default form submission

  const formData = new FormData();
  const itemName = document.getElementById('itemName').value;
  const itemPrice = document.getElementById('itemPrice').value;
  const itemImage = document.getElementById('itemImage').files[0]; // Get the File object

  // Append text fields
  formData.append('name', itemName);
  formData.append('price', itemPrice);

  // Append the file
  if (itemImage) {
    formData.append('image', itemImage, itemImage.name); // 'image' is the field name on the server
  } else {
    console.warn('No image selected for upload.');
  }

  try {
    const response = await fetch(API_UPLOAD_URL, {
      method: 'POST',
      body: formData, // No need to set 'Content-Type', fetch does it automatically for FormData
      // You might need to add authorization headers here
      // headers: {
      //   'Authorization': 'Bearer YOUR_AUTH_TOKEN',
      // }
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`Upload failed: ${response.status} ${errorData.message || ''}`);
    }

    const result = await response.json();
    console.log('Upload successful:', result);
    alert('Item uploaded successfully!');
  } catch (error) {
    console.error('Error during upload:', error);
    alert(`Error uploading item: ${error.message}`);
  }
});
How it works: This JavaScript snippet demonstrates how to perform a file upload to an API using `multipart/form-data` from a web browser. It uses the `FormData` API to construct the request body, allowing both text fields (like `name` and `price`) and binary files (like `itemImage`) to be sent in a single `POST` request. The `fetch` API is then used to send this data, automatically setting the correct `Content-Type` header for `multipart/form-data` submissions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs