Pen*_*gin 5 javascript mongoose node.js express multer
我在将图像文件上传到我的服务器时遇到问题,我在 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'))
Run Code Online (Sandbox Code Playgroud)
图像架构和模型:
const imageSchema = new mongoose.Schema({
profilePicture: String
})
const Image = new mongoose.model('Image', imageSchema)
Run Code Online (Sandbox Code Playgroud)
我的邮寄路线:
app.post('/changeProfilePic', upload.single('profilePicture'), function(req, res, next){
console.log(req.file);
const newImage = new Image({
profilePicture: req.file.path
})
newImage.save()
})
Run Code Online (Sandbox Code Playgroud)
我的 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>
Run Code Online (Sandbox Code Playgroud)
当我记录 (req.file) 的值时,它说它的类型是“未定义”,所以这一定意味着 multer 没有识别甚至没有收到图像文件。我做错了什么,multer 没有得到文件?
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |