Nima Kaviyani
Nima Kaviyani

Reputation: 113

How to uploading file with ReactJS and Axios

Using react-bootstrap form for post a file and some data:

<Form
    onSubmit={this.handleSubmit}
>
    <Form.Group controlId="newTeacher.name">
        <Form.Label>Teacher Name</Form.Label>
        <Form.Control
            type="text"
            name="name"
        />
    </Form.Group>
    <Form.Group controlId="newTeacher.description">
        <Form.Label>Description</Form.Label>
        <Form.Control
            as="textarea"
            rows="3"
            name="description"
            placeholder="Description"
        />
    </Form.Group>
    <Form.Group controlId="newTeacher.avatar">
        <Form.Label>Avatar</Form.Label>
        <Form.Control
            type="file"
            name="avatar"
        />
    </Form.Group>
    <Button
        variant="primary"
        type="submit"
    >Save Teacher</Button>
</Form>

When I try send data with Axios to server:

handleSubmit = (e) => {
    if (e && e.preventDefault()) e.preventDefault();

    const formData = new FormData(e.target);

    const name = formData.get('name');
    const content = formData.get('description');
    const avatar = formData.get('avatar');

    const requestBody = {
        name,
        content,
        avatar,
        token: cookie.getItem('token'),
    };

    axios.post(apiUrl + "/api/v1/admin/teacher", requestBody,
        {
            mode: 'cors',
            headers: 'multipart/form-data'
        }
    ).then(response => {
        console.log('response:');
        console.log(response);
    }).catch(error => {
        console.log('reject:');
        console.log(error);
    });
};

When I submit form, this is the what is returned in the console (This is the reject message from Axios.):

reject: TypeError: "name.toUpperCase is not a function"

How can I fix it?

Update: This script not work properly. I will update this for those who have this problem.

Data must be append:

const requestBody = new FormData();
requestBody.append("avatar", avatar);
requestBody.append("name", name);
requestBody.append("content", content);

And multipart/form-data is not necessary. In some cases it has problems with Multer. Also, token should be in the header:

axios.post(apiUrl + "/api/v1/admin/teacher", requestBody,
    {
        mode: 'cors',
        headers: {
            'x-access-token': cookie.getItem('token'),
        }
    }
).then(response => {
    // SOME ACTION.
})

Upvotes: 2

Views: 2025

Answers (1)

Sohail Ashraf
Sohail Ashraf

Reputation: 10604

Axios expecting headers as an object, So pass the headers as object.

Example

 axios.post(apiUrl + "/api/v1/admin/teacher", requestBody,
      {
            mode: 'cors',
            headers: { 'Content-Type':  'multipart/form-data' }
      }
 ).then(response => {
     //...
 });

Upvotes: 3

Related Questions