← Back to all snippets
JAVASCRIPT

Posting Form Data (Multi-part) to an API in JavaScript

Discover how to post HTML form data, including file uploads, to a REST API using JavaScript's FormData object and the Fetch API for multi-part/form-data requests.

async function postFormData(url, formElement) {
  try {
    const formData = new FormData(formElement);
    // If you need to add extra data not in the form:
    // formData.append('customField', 'someValue');

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

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const result = await response.json();
    return result;
  } catch (error)
  {
    console.error("Failed to post form data:", error);
    throw error;
  }
}

// Example Usage (assuming you have an HTML form like <form id="my-form">...</form>):
/*
document.addEventListener('DOMContentLoaded', () => {
  const myForm = document.getElementById('my-form');
  if (myForm) {
    myForm.addEventListener('submit', async (event) => {
      event.preventDefault(); // Prevent default form submission
      try {
        const result = await postFormData('/api/upload', myForm);
        console.log('Upload successful:', result);
        alert('Form submitted successfully!');
      } catch (error) {
        console.error('Submission failed:', error);
        alert('Error submitting form.');
      }
    });
  }
});
*/
How it works: This JavaScript snippet shows how to submit an HTML form's data, including text fields and file inputs, to a REST API. It utilizes the `FormData` object to easily construct a `multipart/form-data` request body, which is then sent using the `fetch` API. This is crucial for integrating forms that require file uploads or complex data submission with backend APIs, complete with robust error handling.

Need help integrating this into your project?

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

Hire DigitalCodeLabs