What is the correct way to upload a file using JavaScript, and how can I send it to a server while listening for upload completion?

One of the most classic ways to handle file uploads in JavaScript is by using FormData with XMLHttpRequest. It gives you good control over the request and lets you listen for progress or completion events.

function uploadFile() {
  const fileInput = document.getElementById("image-file");
  const file = fileInput.files[0];

  const formData = new FormData();
  formData.append("file", file);

  const xhr = new XMLHttpRequest();
  xhr.open("POST", "/upload/image");

  xhr.onload = function () {
    if (xhr.status === 200) {
      console.log("Upload complete!");
    } else {
      console.error("Upload failed.");
    }
  };

  xhr.send(formData);
}

If you’re looking to upload file JavaScript style with full control, this is a solid, browser-friendly choice, especially for handling things like progress bars and response handling.