Categories
JavaScript Answers

How to upload file without form with JavaScript?

Spread the love

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

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

How to upload file without form with JavaScript?

To upload file without form with JavaScript, we can create a FormData object with the file.

For instance, we write

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

to add a file input.

Then we write

const input = docucment.querySelector("input");
input.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 the input with querySelector.

Then we set the input.onchange property to a function that runs when we change the file selection.

In it, we create a FormData object.

And we call append to put the file inside with key e.target.name.

e.target.name is the input’s name attribute’s value.

e.target.files[0] is the first selected file.

Then we call fetch with the URL to upload the file to and an object with the body property set to formData to make the upload request.

Conclusion

To upload file without form with JavaScript, we can create a FormData object with the file.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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