Categories
React Answers

How to Send Multipart Form Data with Axios in a React Component?

Spread the love

Sometimes, we want to make requests with file data in the request payload.

In this article, we’ll look at how to make requests with file data in the request payload.

Send Multipart Form Data with Axios in a React Component

We can send form data with the FormData constructor.

We can pass that straight into the Axios post method.

For instance, we can write:

import React from 'react'
import axios, { post } from 'axios';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault()
    const url = 'http://example.com/upload';
    const formData = new FormData();
    formData.append('file', this.state.file);
    const config = {
      headers: {
        'content-type': 'multipart/form-data'
      }
    }
    post(url, formData, config);
      .then((response) => {
        console.log(response.data);
      })
  }

  onChange(e) {
    this.setState({ file: e.target.files[0 ]})
  }

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

We have a file input, where we set the file input to the file that’s submitted in the onChange method.

We save the selected file object as the value of the file state.

Then when we click the Upload button, onFormSubmit is run.

In the method, we created a FomrData instance.

Then we append our file into the FormData instance.

We also set the header so that we indicate that we’re sending form data.

Once we did that, we proceed with our file upload.

Conclusion

We can send form data with the FormData constructor.

And we can pass that straight into the Axios post method.

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 *