我有一个Express应用程序,通过表单从用户获取图像。我需要对图像做一些事情,因为它变得越来越复杂,我不知道如何处理它。这是一个留言板帖子,其中包含一些必需的文本字段和可选的图像上传。我需要:
我很关心我正在做的事情的顺序,想知道是否有更有效的方法。我知道我可以在路由中调用upload
而不是传入它,但是当我将记录保存到数据库时我不想重复自己,因为无论是否有图像我都需要保存它。
我的代码适用于最后的3个步骤,但我们对如何改进它的建议持开放态度。第一步,我很难理解如何获得原件的方向并根据需要旋转它。这是我需要做客户端的事吗?我如何将其用于现有代码?
以下是代码:
设置
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads');
},
filename: function (req, file, cb) {
var fileExt = file.mimetype.split('/')[1];
if (fileExt == 'jpeg'){ fileExt = 'jpg';}
cb(null, req.user.username + '-' + Date.now() + '.' + fileExt);
}
})
var restrictImgType = function(req, file, cb) {
var allowedTypes = ['image/jpeg','image/gif','image/png'];
if (allowedTypes.indexOf(req.file.mimetype) !== -1){
// To accept the file pass `true`
cb(null, true);
} else {
// To reject this file pass `false`
cb(null, false);
//cb(new Error('File type not allowed'));// How to pass an error?
}
};
var upload = multer({ storage: storage, limits: {fileSize:3000000, fileFilter:restrictImgType} });
在路线
router.post('/new',upload.single('photo'),function(req,res){
var photo = null;
var allowedTypes = ['image/jpeg','image/gif','image/png'];
if (req.file){
photo = '/uploads/' + req.file.filename;
// save thumbnail -- should this part go elsewhere?
im.crop({
srcPath: './public/uploads/'+ req.file.filename,
dstPath: './public/uploads/thumbs/100x100/'+ req.file.filename,
width: 100,
height: 100
}, function(err, stdout, stderr){
if (err) throw err;
console.log('100x100 thumbnail created');
});
// I can get orientation here,
// but the image has already been saved
im.readMetadata('./public/uploads/'+ req.file.filename, function(err, metadata){
if (err) throw err;
console.log("exif orientation: " + metadata.exif.orientation);
});
}
// Save it
new Post({
username: req.user.username,
title: req.body.title,
body: req.body.messagebody,
photo: photo
}).save(function(err){
if (err){ console.log(err); }
res.redirect('/messageboard');
});
});
感谢您的帮助