2
無論我如何實現文件上傳,當檢查Express中請求的req.file
屬性時,我會得到undefined
。Multer通過ReactJS返回`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( '文件')'呢? – Panther