我在将图像文件上传到我的服务器时遇到问题,无论出于何种原因,我都收到错误:(“TypeError:无法读取未定义的属性'路径'”)。我在谷歌上搜索了这个错误,发现有些人遇到了同样的问题,我试图像他们一样解决它,但它对我不起作用。
这是我的代码:
const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './public/images/profilePictures');
},
filename: function(req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
app.use(express.static('public'))
映像架构和模型:
const imageSchema = new mongoose.Schema({
profilePicture: String
})
const Image = new mongoose.model('Image', imageSchema)
我的帖子路线:
app.post('/changeProfilePic', upload.single('profilePicture'), function(req, res, next){
console.log(req.file);
const newImage = new Image({
profilePicture: req.file.path
})
newImage.save()
})
我的html上传表格:
<form action="/changeProfilePic" method="POST" enctype = "multipart/form-data">
<input type="file" name="profilePicture" placeholder="Image" />
<button class="btn btn-light btn-lg" type="submit">Upload</button>
</form>
当我记录 (req.file) 的值时,它说它的类型是“未定义”,所以这一定意味着 multer 没有识别甚至没有收到图像文件。我做错了什么,Multer 没有得到文件?
侃侃尔雅
相关分类