我想从React开发的前端上传文件,并在Express js中获得上传的文件。
下面是我上传文件时React端的代码片段:
handleUploadFile(ev) {
ev.preventDefault();
var a6 = "File";
const data = new FormData();
data.append('file', this.uploadInput.files[0]);
data.append('fileName', a6);
fetch('http://localhost:4000/api/addDcuments/upload', {
method: 'POST',
body: {data},
json: true,
headers: { "Authorization": cookie.load('userToken') }
}).then((response) => {
response.json().then((body) => {
this.setState({ imageURL: `http://localhost:4000/${body.file}` });
});
});
}
在上面的代码中,我采用了形式,并在它的onSubmit事件上调用了handleUploadFile函数。
现在,下面是我的后端express js代码,我在它上面得到了上传的文件:
export function uploadDocument(req, res, next) {
console.log(JSON.stringify(req.body));
let imageFile = req.files.file;
var ext = path.extname(imageFile.name)
if(imageFile.mimetype == "application/pdf" ||imageFile.mimetype == "application/octet-stream"){
imageFile.mv('D:/React Workspace/React-videos-example/file_path/'+req.body.filename+ext, function(err) {
if (err) {
return res.status(500).send(err);
}
res.json({file: `public/${req.body.filename}.pdf`});
});
}
}
在上面的代码中,当我尝试打印req.body
时,它返回"{}“,并且我得到一个错误:
文件:无法读取未定义的属性‘TypeError’。
因此,我的后端函数已被调用,但无法获取上传的文件。那么,对于这个问题,任何人都可以有任何解决方案或参考链接吗?
发布于 2018-08-21 05:25:46
当使用formdata时,你不能在帖子中使用json类型,它需要是:
contentType:‘多部分/表单数据’
而不是"json: true“。
https://stackoverflow.com/questions/51932854
复制相似问题