Home > other >  How can I make onSumbit react the same as action/method of a form?
How can I make onSumbit react the same as action/method of a form?

Time:04-06

I am trying to save files to a server using multer, but I want the form to save the files through onSubmit instead of posting through the method/action of the form.

Is this possible?

In the example below, I am posting to the server using the method/action and it works perfectly.

 <form
    action="<URL>"
    method="POST"
    encType="multipart/form-data"
    // onSubmit={documentUpload}
    className="upload-files"
   >
   <input type="file" name="file" />
   <button>Submit File</button>
</form>

but I want the same thing to happen when I use onSubmit. Here is the code for documentUpload:

 const documentUpload = async () => {
    const formData = new FormData();

    await fetch("<URL>", {
      method: "POST",
      body: formData,
    });
  };

CodePudding user response:

You can just avoid to use a <form> element:

 <div
   className="upload-files"
 >
   <input type="file" name="file" />
   <button onClick={documentUpload}>Submit File</button>
</div>

CodePudding user response:

Found the solution. I had to give my form an ID:

<form
    onSubmit={documentUpload}
    className="upload-files"
    id="myForm"
  >
    <input type="file" name="file" />
    <button>Submit File</button>
  </form>

And then I had to get the form by ID and push it into the first parameter of FormData:

const documentUpload = async (e) => {
let myForm = document.getElementById("myForm");
const formData = new FormData(myForm);

await fetch("<URL>", {
  method: "POST",
  body: formData,
});};

For more info: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

  • Related