【发布时间】:2018-02-04 09:39:50
【问题描述】:
无论我如何实现文件上传,当在 Express 中检查请求的 req.file 属性时,我都会返回一个 undefined。
..
反应代码
组件:
import Files from 'react-files';
<form encType="multipart/formdata">
<Files
ref='files'
onChange={this.onFileUpload}>
</Files>
</form>
方法:
onFileUpload (files) {
let reader = new FileReader();
reader.onload = upload => {
this.setState({
dataURI: upload.target.result
}, () => {
if (typeof appState.balance == 'number' && appState.balance > 0) {
appState.onFileAdd(files, this.state.dataURI);
} else {
this.setState({ modal: true });
}
});
}
reader.readAsDataURL(files[files.length - 1]);
}
这可以正常工作;状态中的dataURI 值是合法的并且设置正确。
..
API 调用代码
export async function funFile(name, dataURI) {
let data = new FormData();
data.append('file', dataURI);
data.append('name', name);
return await fetch('http://localhost:1185/fun',
{ method: 'POST', data }).then(res => {
if (res.ok && res.status == 200) {
return res.json();
} else {
return null;
}
});
}
在此处检查 data 会返回预期的 FormData 对象,但无法查看分配的 name 和 file 属性(无论是因为它们未正确分配还是这是我的预期行为不确定)。
..
快递代码
var multer = require('multer');
var upload = multer({ destination: 'uploads/' });
app.post('/fun', upload.single('file'), (req, res) => {
console.log('file', req.file);
console.log('files', req.files);
// both of these return undefined
});
无论我此时做什么,请求都不会返回文件数据。 req.body 属性也是空的。
我不确定这里到底哪里出了问题,并且从关于这个实现的所有可能的教程和演练中,我已经尝试了我能想到的所有可能的语法排列,所以任何帮助都非常感谢!
【问题讨论】:
-
你的
upload.single('file')是做什么的?
标签: node.js reactjs express filereader form-data