首页 > 解决方案 > 如何使用 ReactJS 和 Axios 上传文件

问题描述

使用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>

当我尝试使用 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);
    });
};

当我提交表单时,这是控制台中返回的内容(这是来自 Axios 的拒绝消息。):

拒绝: TypeError:“name.toUpperCase 不是函数”

我该如何解决?

更新: 此脚本无法正常工作。我会为那些有这个问题的人更新这个。

数据必须是append

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

并且multipart/form-data没有必要。在某些情况下,它与Multer. 此外,令牌应该在标题中:

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

标签: javascriptreactjsapiaxiosreact-bootstrap

解决方案


Axios期望标头作为对象,因此将标头作为对象传递。

例子

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

推荐阅读