我在将图像文件上传到我的服务器时遇到问题,我在 YouTube 上观看了关于 multer 的教程,我做了与教程中完全相同的事情,无论出于何种原因,我都收到错误:(“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没有得到文件?
最佳答案
我将目的地更改为 ./uploads
对我来说很好
关于javascript - multer npm : TypeError: Cannot read property 'path' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65270771/