JAVASCRIPT

Uploading Files to an API with FormData and Fetch

Discover how to upload files, like images or documents, to a backend API endpoint using JavaScript's FormData object and the fetch API for robust data transfer.

async function uploadFile(fileInputId, uploadUrl) {
  const fileInput = document.getElementById(fileInputId);
  const file = fileInput.files[0];

  if (!file) {
    console.error("No file selected.");
    return;
  }

  const formData = new FormData();
  formData.append("file", file); // 'file' is the field name expected by your API
  formData.append("description", "A file uploaded via JavaScript"); // Add other form data if needed

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

    if (!response.ok) {
      throw new Error(`Upload failed with status: ${response.status}`);
    }

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

// Example usage (assuming an <input type="file" id="myFileInput"> exists):
// const uploadBtn = document.getElementById("uploadButton");
// uploadBtn.addEventListener("click", () => {
//   uploadFile("myFileInput", "/api/upload")
//     .then(res => console.log("Upload response:", res))
//     .catch(err => console.error("Upload error:", err));
// });
How it works: This snippet demonstrates how to upload a file from a web form to an API endpoint. It uses the `FormData` object to construct a `multipart/form-data` request, which is ideal for sending both files and other textual data. The `fetch` API then sends this `FormData` to the specified `uploadUrl`, handling the complexities of file transfer.

Need help integrating this into your project?

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

Hire DigitalCodeLabs