Published on

How to Upload File using axios and redux form

Authors

In this article, I'll explain about how to upload a file using axios and redux-form

First, you need to download required packages using npm package manager

npm install --save react axios redux-form

And configure redux-form in your application accordingly. Since it depends on your project structure I'm skipping that part.

Then you need to create a component to handle form submit. For the sake of simplicity I'm doing all the ajax calls within the component itself. In your application, you would do it in your redux action.

import React from 'react';
import { Field, reduxForm } from 'redux-form';
import { post } from 'axios';
export const FileUpload = props => {
  const { handleSubmit } = props;
  const onFormSubmit = data => {
    let formData = new FormData();
    formData.append('name', data.name);
    formData.append('profile_pic', data.profile_pic[0]);
    const config = {
      headers: { 'content-type': 'multipart/form-data' },
    };
    const url = 'http://example.com/fileupload/';
    post(url, formData, config)
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  };
  return (
    <form onSubmit={handleSubmit(onFormSubmit)}>
      <div>
        <label>Name</label>
        <Field name="name" component="input" type="text" />
      </div>
      <div>
        <label>Profile Picture</label>
        <Field name="profile_pic" component="input" type="file" />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default reduxForm({
  form: 'fileupload',
})(FileUpload);

That's it!