我已经完全死胡同了。我一直在寻找SO的答案,已经有好几个小时了,而且似乎什么也没用。
反应应用
Axios专用的Axios
尝试使用multer将文件发布到Express端点。
我的终点:
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
router.post("/", upload.single("file"), async (req, res) => {
let file = req.file.buffer; //...file is undefined from Axios, has buffer from Postman and works
//...etc...
});
我的表单:
onChangeFile = e => {
let file = e.target.files[0];
let formData = new FormData();
formData.append("file", formData);
const reqParams = {
method: "POST",
url: `https://myapi.com/documents`,
data: {
"file": formData
},
headers: {
"my_custom_header": "ABC123"
}
};
axios(reqParams)
.then(result => console.log(JSON.stringify(result, null, 4)))
.catch(e => console.log(e));
}
render() {
<form encType="multipart/form-data">
<input type="file" name="file" id="file" onChange={this.onChangeFile} />
</form>
}
Axios结果从上面输出:
{
"data": [
{
"source": "system",
"type": "json",
"status": 200,
"reason": null,
"message": "Successful",
"error": false,
"date": "2018-08-28T21:35:36.000Z",
"payload": {
"my_custom_header": "ABC123",
"file": {}
}
}
],
"status": 200,
"statusText": "OK",
"headers": {
"content-type": "application/json; charset=utf-8"
},
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
"my_custom_header": "ABC123"
},
"method": "post",
"url": "https://myapi.com/documents",
"data": "{\"file\":{}}"
},
"request": {}
}
端点从Postman可以正常工作。我最初关注这篇文章:https://blog.stvmlbrn.com/2017/12/17/upload-files-using-react-to-node-express-server.html