Categories
React Answers

How to set multipart in Axios with React?

Spread the love

Sometimes, we want to set multipart in Axios with React.

In this article, we’ll look at how to set multipart in Axios with React.

How to set multipart in Axios with React?

To set multipart in Axios with React, we can submit a FormData object when making the request.

For instance, we write

const Comp = () => {
  const [file, setFile] = useState();

  const fileUpload = (file) => {
    const url = "http://example.com/file-upload";
    const formData = new FormData();
    formData.append("file", file);
    const config = {
      headers: {
        "content-type": "multipart/form-data",
      },
    };
    return post(url, formData, config);
  };

  const onFormSubmit = (e) => {
    e.preventDefault();
    const { data } = await fileUpload(file);
  };

  const onChange = (e) => {
    setFile(e.target.files[0]);
  };

  return (
    <form onSubmit={onFormSubmit}>
      <h1>File Upload</h1>
      <input type="file" onChange={onChange} />
      <button type="submit">Upload</button>
    </form>
  );
};

to create the Comp component.

In it, we define the file state with useState.

Then we define the fileUpload function that creates a FormData object.

Next, we add the file object into the FormData object with append.

And then we make the request with the Axios post method with the url, formData object and the config that has the headers that sets content-type header to multipart/form-data.

Next, we define the onFormSubmit function that calls preventDefauly to stop the default form submit behavior.

And then we call fileUpload to upload the file.

Finally, we render a form element with a file input in it.

When the file selection is changed, onChange is called.

And onFormSubmit is called when we click Upload.

Conclusion

To set multipart in Axios with React, we can submit a FormData object when making the request.

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 *