Multer使用ReactJS返回未定义的file upload文件

无论我如何实现file upload,在Express中检查请求的req.file属性时, 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对象,虽然没有能力看到分配的namefile属性(无论是因为他们没有正确分配或这是预期的行为,我不知道)。

..

快速代码

 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属性也是空的。

我不确定事情在哪里出了问题,从这个实现的所有可能的教程和演练中,我尝试了所有可能的语法变换,我可以想到的,所以任何帮助表示赞赏!

我相信问题是读取文件作为数据的URL。 忘记FileReader 。 你不需要读取任何东西,只需要将一个文件对象传递给你的FormData ,你就应该被设置好了。

的onChange

 onFileUpload (files) { this.setState({ file: files[files.length-1] }, () => { if (typeof appState.balance == 'number' && appState.balance > 0) { appState.onFileAdd(files, this.state.file); } else { this.setState({ modal: true }); } }); } 

API调用

 export async function funFile(name, file) { let data = new FormData(); data.append(name, file); // name here should be avatar return await fetch('http://localhost:1185/fun', { method: 'POST', data }).then(res => { if (res.ok && res.status == 200) { return res.json(); } else { return null; } }); }