我正在尝试使用multer
从表单上传图片,但每次req.files
和req.file.path
都会在我的控制台日志中返回undefined
。
我也遇到了这个错误:
TypeError: Cannot read property 'path' of undefined
这是我的表单代码:
<form action="/admin/home/add-category" method="post" enctype="multipart/form-data">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add Category</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Title</label>
<input name="title" class="form-control" type="text" placeholder="Category Title"> <br>
<label>Upload Image</label>
<input name="cat_image" class="form-control" type="file" accept="image/*" id="selImg" onchange="showImage.call(this)">
<img src="#" id="imgPreview" style="display: none; height: 100px; width: 100px">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
和我的配置multer的代码:
const multer = require('multer');
const storage = multer.diskStorage({
destination: ((req, file, cb) => {
cb(null, 'uploads/category_images/');
}),
filename: ((req, file, cb) => {
cb(null, file.originalname);
})
});
const fileFilters = (req, file, cb) => {
if (file.mimeType === 'image/jpeg' || file.mimeType === 'image/jpg' ||
file.mimeType === 'image/png') {
cb(null, true);
} else {
//cb(new Error('Image must be .jpeg, .jpg or .png format'), false);
cb(null, false);
}
};
const uploads = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 2
},
fileFilter: fileFilters
});
以及上传图片的代码:
router.post('/add-category', uploads.single('cat_image'), (req, res) => {
console.log(req.files); // undefined
console.log(req.filename); // undefined
let title = req.body.title;
console.log('Category Title:\t' + title);
let slug = title.replace(/\s+/g, '-').toLowerCase();
let catImage = req.file.path; // error here
console.log(catImage);
let category = new Category({
title: title,
slug: slug,
image: catImage
});
category.save()
.then(result => {
if (result) {
console.log('Saved Category:\t' + result);
res.redirect('/admin/home');
}
})
.catch(errors => {
console.error('Error Saving Category:\t' + errors);
});
});
我一整天都在努力解决这个问题。任何人都可以帮助我理解为什么它不能解决这个问题? 感谢。
答案 0 :(得分:0)
我已经使用cloudinary service
摆脱了所有麻烦,因为他们已经有sdk for node
。我没有在这里宣传任何东西,只希望没有其他人面对这个问题。