9.6 node系列(multer,markdown)

1.multer

var multer = require('multer');
multer用于图片上传,
1.方法一(图片名称不能自定义)
var upload = multer({dest:'../public/uploads/'})
2.方法二(图片名称能自定义)

var storage = multer.diskStorage({
    destination : function (req,file,cb) {
        cb(null,'../public/uploads/')
    },
    filename: function (req,file,cb) {
        cb(null, Date.now()+path.extname(file.originalname))
    }
})
var upload = multer({storage:storage})

../public/uploads/工程内部路径,存放上传上来的图片

然后再post的请求中加入upload.single('img'), 然后再model类中加入图片的路径,代码如下

router.post('/add',auth.mustLogin,upload.single('img'), function(req, res, next) {
    console.log(req.file);
    var article = req.body;
    if(req.file){
        article.img = path.join('/uploads',req.file.filename);
    }

    var user = req.session.user;
    article.user = user._id;

    new Model('Article')(article).save(function (err,doc) {
        if(err){
            console.error(err);
            req.flash('error', '文章发表失败');
            return res.redirect('back');
        }else{
            req.flash('success', '文章发表成功');
            res.redirect('/');
        }
    })
});

2. markdown

var markdown = require('markdown').markdown;
导入markdown
article.content = markdown.toHTML(article.content);
用来显示的content 要这样来写
<%-article.content%>

你可能感兴趣的:(9.6 node系列(multer,markdown))