简体   繁体   English

如何使用 ReactJS 和 Axios 上传文件

[英]How to uploading file with ReactJS and Axios

Using react-bootstrap form for post a file and some data:使用react-bootstrap表单发布文件和一些数据:

<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:当我尝试使用 Axios 将数据发送到服务器时:

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.):当我提交表单时,这是控制台中返回的内容(这是来自 Axios 的拒绝消息。):

reject: TypeError: "name.toUpperCase is not a function"拒绝:类型错误:“name.toUpperCase 不是函数”

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 :必须append数据:

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

And multipart/form-data is not necessary.并且multipart/form-data不是必需的。 In some cases it has problems with Multer .在某些情况下,它与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.
})

Axios expecting headers as an object, So pass the headers as object. Axios期望标头作为对象,因此将标头作为对象传递。

Example例子

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM