我想使用玉石表格上传图片然后我想在帖子页面显示问题是图片上传为没有扩展名的文件然后我得到无法读取未定义的属性'mainimage'
我的app.js代码低于
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public/images/uploads/');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({storage: storage}).single('mainimage');
然后我的帖子.js
router.post('/add', function(req, res, nect){
// Get The Form Values
var title = req.body.title;
var category = req.body.category;
var body = req.body.body;
var author = req.body.author;
var date = new Date();
if(req.file.mainimage){
var mainImageOriginalName = req.file.mainimage.originalname;
var mainImageName = req.file.mainimage.name;
var mainImageMime = req.file.mainimage.mimetype;
var mainImagePath = req.file.mainimage.path;
var mainImageExt = req.file.mainimage.extension;
var mainImageSize = req.file.mainimage.size;
} else{
var mainImageName = 'noimage.png';
}
//Form Validation
req.checkBody('title', 'Title field is required').notEmpty();
req.checkBody('body', 'Body field is required');
//Check errors
var errors = req.validationErrors();
if(errors){
res.render('addpost',{
"errors": errors,
"title": title,
"body": body
});
} else{
var posts = db.get('posts');
//submit to db
posts.insert({
"title": title,
"body": body,
"category": category,
"date": date,
"author": author,
"mainimage": mainImageName
}, function(err, post){
if(err){
res.send('There was an issue submitting the post');
} else{
req.flash('success', 'Post Submitted');
res.location('/');
res.redirect('/');
}
});
}
});
这是我的posts.jade表格
form(method='post', action='/posts/add', enctype='multipart/form-data')
.form-group
label Title:
input.form-control(name='title', type='text')
.form-group
label Category
select.form-control(name='category')
each category, i in categories
option(value='#{category.title}') #{category.title}
.form-group
label Body
textarea.form-control(name='body', id='body')
.form-group
label Main Image:
input.form-control(name='mainimage', type='file', id='mainimage')
以下是我要展示的地方
each post, i in posts
.posts
h1
a(href='/posts/show/#{post._id}')
=post.title
p.meta Posted in #{post.category} by #{post.author} on #{moment(post.date).format('MM-DD-YYYY')}
img(src='/images/uploads/#{post.mainimage}')
!=post.body
a.more(href='/posts/show/#{post._id}') Read More
答案 0 :(得分:0)
扩展程序问题可能是因为在storage
中,您为没有扩展程序的文件命名。
要添加它,您可以在storage
方法中插入此代码。
filename: function (req, file, callback) {
var extension = file.mimetype;
extension = extension.substring(extension.indexOf("/")+1, extension.length);
var filename = file.fieldname + '-' + Date.now() + "." + extension;
callback(null, filename);
}
另外,如果您没有映射目录,可以在app.js
中插入一个静态映射到保存文件的文件夹,如下所示:
app.use('/images', express.static(path.join(__dirname, 'images')));
然后,在post
页面中,您可以使用http://yourdomain:port/images/<filename.extension>
直接通过其网址访问下载的文件。
希望它有所帮助。