怎么用数据库路径返回图片
最近在研究写接口,普通的查询还可以,涉及到图片的有点犯愁了。
理想状态是

【上传图片】
const multer = require('multer')
const express = require('express')
var router = express.Router()
let upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, '../imgs/sy');
        },
        filename: function (req, file, cb) {
            var changedName = (new Date().getTime())+'_'+file.originalname;
            cb(null, changedName);
        }
    })
});
 // 文件上传
 router.post('/single', upload.any(), (req, res,next) => {
    let file = req.files
    let title = req.body.title
    for(let i = 0;i<file.length;i++){
        let path = file[i].path.replace(/\\/g,'/')
        let sql = `INSERT INTO imgs (name,path,type) VALUES ("${file[i].originalname}","${path}","${title}")`
        conn.query(sql,(err,result)=>{
            if(err) throw err
        })
    }
    res.json({
        title,
        fileList: file
    });
 });
这样就把图片上传到了imgs/sy中
文件结构:

但问题是。。。数据库存放的路径是这样的

这路径咋搞嘛。所以【获取图片】先要让图片能够以url形式访问,这就用到了express.static
即用express设置静态目录
const app = express() app.use('/imgs',express.static('../imgs'));//根据自己实际的路径去设置
//例如,通过如下代码就可以将 public 目录下的图片、CSS 文件、JavaScript 文件对外开放访问了 app.use(express.static('public')) http://localhost:3000/images/kitten.jpg http://localhost:3000/css/style.css http://localhost:3000/js/app.js http://localhost:3000/images/bg.png http://localhost:3000/hello.html app.use('/static', express.static('public')) //现在,你就可以通过带有 /static 前缀地址来访问 public 目录中的文件了。 http://localhost:3000/static/images/kitten.jpg http://localhost:3000/static/css/style.css http://localhost:3000/static/js/app.js http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html
然后在浏览器里输入url就可以看到你的图片了

然后把数据库中的path做一下处理返回就可以了
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号