JAVASCRIPT

Upload Files to a REST API using JavaScript FormData

Learn how to upload files, such as images or documents, to a backend REST API endpoint from a web browser using JavaScript's FormData object.

// HTML part (e.g., in index.html):
// <form id="fileUploadForm" enctype="multipart/form-data">
//   <input type="file" id="myFile" name="fileInput" accept=".png,.jpg,.jpeg">
//   <input type="text" id="description" name="fileDescription" placeholder="File Description">
//   <button type="submit">Upload File</button>
// </form>
// <div id="uploadStatus"></div>

document.addEventListener('DOMContentLoaded', () => {
  const form = document.getElementById('fileUploadForm');
  const fileInput = document.getElementById('myFile');
  const descriptionInput = document.getElementById('description');
  const uploadStatus = document.getElementById('uploadStatus');

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

      uploadStatus.textContent = 'Uploading...';
      uploadStatus.style.color = 'blue';

      const selectedFile = fileInput.files[0];
      const fileDescription = descriptionInput.value;

      if (!selectedFile) {
        uploadStatus.textContent = 'Please select a file to upload.';
        uploadStatus.style.color = 'red';
        return;
      }

      const formData = new FormData();
      formData.append('file', selectedFile); // 'file' is the name the backend expects
      formData.append('description', fileDescription); // Add other form fields

      try {
        const response = await fetch('YOUR_FILE_UPLOAD_API_ENDPOINT', {
          method: 'POST',
          body: formData, // FormData automatically sets 'Content-Type': 'multipart/form-data'
          // Do NOT explicitly set 'Content-Type' header when using FormData with fetch,
          // as fetch will set it correctly with the boundary parameter.
        });

        if (response.ok) {
          const result = await response.json();
          uploadStatus.textContent = `Upload successful: ${result.message || 'File uploaded.'}`;
          uploadStatus.style.color = 'green';
          console.log('Backend response:', result);
          // Clear form or reset
          form.reset();
        } else {
          const errorData = await response.json();
          uploadStatus.textContent = `Upload failed: ${errorData.message || response.statusText}`;
          uploadStatus.style.color = 'red';
          console.error('Upload failed:', errorData);
        }
      } catch (error) {
        uploadStatus.textContent = `Network error: ${error.message}`;
        uploadStatus.style.color = 'red';
        console.error('Network or server error:', error);
      }
    });
  }
});
How it works: This JavaScript snippet demonstrates how to upload files to a REST API endpoint from a web browser. It leverages the `FormData` API to construct a `multipart/form-data` request body, which is the standard way to send files along with other form data (like descriptions or metadata). The `fetch` API is then used to send this `FormData` object to the specified backend endpoint, handling both successful responses and potential errors during the upload process.

Need help integrating this into your project?

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

Hire DigitalCodeLabs