javascript - 如何使用 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.
})
解决方案
Axios
期望标头作为对象,因此将标头作为对象传递。
例子
axios.post(apiUrl + "/api/v1/admin/teacher", requestBody,
{
mode: 'cors',
headers: { 'Content-Type': 'multipart/form-data' }
}
).then(response => {
//...
});
推荐阅读
- firebase - SwiftUI Firebase 如何进行自定义错误处理
- java - 获取最近的范围时间表
- javascript - 使用 javascript 和 php 通过 nft.storage 在 IPFS 上上传和显示图像
- kubernetes - GCP:在 GKE 上安装 Kafka - zookeeper 未启动
- pointers - cudaMemcpy 来自内核中分配的内存
- javascript - 如何通过代码从 DataGrid MUI 中清除复选框的选择?
- python - 将 Pydantic 模型转换为 Dict 效率不高吗?
- python - 用于在 python 中生成文本的文本 GAN
- python - 我可以在不丢失该数据框引用的情况下更改 dict 中数据框的内容吗?
- xml - Alfresco Share Community 7.0 可以处理多少模型?