How to upload a file without a form with JavaScript?

Spread the love

Sometimes, we want to upload a file without a form with JavaScript.

In this article, we’ll look at how to upload a file without a form with JavaScript.

How to upload a file without a form with JavaScript?

To upload a file without a form with JavaScript, we use fetch.

For instance, we write

<input type="file" name="fileInput" />

to add a file input.

Then we write

const fileInput = document.querySelector("input");

fileInput.onchange = async (e) => {
  const formData = new FormData();
  formData.append(e.target.name, e.target.files[0]);

  const response = await fetch("/api/upload", {
    method: "POST",
    body: formData,
  });

  const result = await response.json();
  console.log(result.message);
};

to select thge input with querySelector.

Then we set its onchange property to a function that create a FormData object.

Then we add the selected file to it with append.

e.target.name is the key.

And e.target.files[0] is the first file selected, which is the value.

Next we call fetch with the URL and an object that sets the body to the formData to doi the upload.

Finally, we call response.json to get the response body as JSON.

Conclusion

To upload a file without a form with JavaScript, we use fetch.

Leave a Reply

Your email address will not be published. Required fields are marked *