我正在通过Express Server(Node)和React将一些个人信息上传到Mongo DB。问题是文件没有上载到服务器上的“上载目录”,在数据库上,我可以看到带有文件名的伪造文件路径。如何检索要显示给用户的文件?我可以检索其他个人信息
下面是代码 这是上传中间件
const path = require('path')
const multer = require('multer')
var storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, __dirname + '/uploads')
},
filename: function(req, file, cb){
let ext = path.extname(file.originalname)
cb(null, Date.now() + ext)
}
})
var upload = multer ({
storage: storage,
fileFilter: function(req, file, callback){
if(
file.mimetype == "image/png" ||
file.mimetype == "document/pdf" ||
file.mimetype == "document/docx"
){
callback(null, true)
}
else{
console.log('Only png, pdf and Docx FILES ALLOWED')
callback(null, false)
}
},
limits: {
fileSize: 1024 * 1024 * 2
}
})
这是“添加项目”控制器
exports.add = (req, res, next) =>{
const { title, category, duration, durationSys, description, budget, addedBy, active,avatar} = req.body
let newProject = new Project({
title,
category,
duration,
durationSys,
description,
budget,
addedBy,
active,
avatar
})
if(req.file){
newProject.avatar = req.file.path
}
newProject.save()
.then(response =>{
res.json({
message: 'Project added successfully'
})
.catch(error =>{
res.json({
message: 'An error ocurred. Try again'
})
})
})
};
这是路线
router.post('/addproject', upload.single("avatar"), add)
前端
const Project= ({history}) => {
const [values, setValues] = useState({
title: '',
category: '',
duration:'',
durationSys: '',
description: 'Describe your project vividly here',
avatar: '',
active:'true',
budget:'',
addedBy: (isAuth().email),
buttonText: 'Post'
});
const { title, category, duration, durationSys,description,avatar,
active,addedBy, budget, buttonText } = values;
const handleChange = name => event => {
setValues({ ...values, [name]: event.target.value } );
};
const clickSubmit = event => {
event.preventDefault();
setValues({ ...values, buttonText: 'Posting Project...' });
console.log(avatar)
axios({
method: 'POST',
url: `${process.env.REACT_APP_API}/addproject`,
data: { title, category, duration, durationSys, description,
avatar, active, addedBy, budget }
})
.then(response => {
console.log('PROJECT ADD SUCCESS', response);
setValues({ ...values, title: '', category: '', duration:
'', durationSys: '',budget: '', description:'',avatar: '',
addedBy: '', buttonText: 'Success' });
toast.success(response.data.message);
})
.catch(error => {
console.log('PROJECT ADD ERROR', error.response.data);
setValues({ ...values, buttonText: 'Try Again' });
toast.error(error.response.data.error);
});
};