概述

后端上传图片一般把图片存入文件夹中,然后把图片的链接写入数据库,前端访问时后端返回数据库中图片的链接

开始操作

var multer = require('multer');
var upload = multer({dest: '../public/upload_tmp/'});
router.post('/upload', upload.any(), function (req, res) {
    // console.log(req);  // 上传的文件信息
    let name = (new Date()).getTime()
    var des_file = '../public/idCardImage/' + req.files[0].originalname;
    console.log(req.files[0].originalname)
    fs.readFile(req.files[0].path, function (err, data) {
        fs.writeFile(des_file, data, function (err) {
            if (err) {
                console.log(err);
            } else {
                let response = {
                    message: '图片上传成功',
                    filename: req.files[0].originalname
                };
                // console.log(response);
                res.json(response)
            }
        });
    });
})

测试

用postman做测试
图片说明
图片说明