node.js写后端接口返回图片

这篇有点问题 等我再写写看 别用!!这篇返回的是绝对路径 浏览器用不了!!

node.js写后端接口返回图片

其实这个跟之前那篇差不多,我采用的是数据库存图片相对路径,接口返回图片的绝对路径(用的__dirname)

文件结构

在这里插入图片描述

tools/pathProcessing.js(路径处理函数)

因为写的是前后端分离,如果直接返回相对路径前端拿到相对路径就去前端的文件夹那里去找了,实际根本没有。所以目前的想法是利用__dirname返回绝对路径。

因为图片存在了public/img/swiper,在路由上几层的文件夹所以要用要对路径进行处理。

tool/pathProcessing.js

// 处理绝对路径的路径处理函数
// dirname=>__dirname(目前的绝对地址) num往上走几层
function pathProcessing(dirname,num){
    let localString=dirname
    let locationArr=localString.split("\\").slice(0,-num).join("\\")
    return locationArr;
}
module.exports =pathProcessing ;
// pathProcessing(__dirname,1)
router/img/swiper.js(图片接口)

返回的是一组图片的绝对路径

const { pool, router } = require("../../connect");
// 导入路径处理函数
const pathProcessing = require("../../tools/pathProcessing");

var path = require("path");

// 返回的数据库数据
// 要改成自己的数据
function Result({ img_id = "", img_name = "", location = " ", img_type = "" }) {
  // console.log(a)
  this.img_id = img_id;
  this.img_name = img_name;
  this.location = location;
  this.img_type = img_type;
}

router.get("/img/swiper", (req, res) => {
  pool.getConnection((err, conn) => {
    //这个sql语句要改成自己的用的
    conn.query("SELECT * FROM mall.swiper;", (e, results) => {
      if (e) throw error;
      var dataString = JSON.stringify(results);
      var data = JSON.parse(dataString);
      imgLocation_arr = new Array();     
      let img;
      for (let index in data) {
        img=new Result(data[index])
        let imgObj={}
        imgObj.img_id=img.img_id
        let imgLocation=img.location+img.img_name+img.img_type
        //这里可以使用replaceAll 我的node.js好像版本不够 就不支持 我也懒得更新了 有兴趣的可以试试看
        imgLocation=(pathProcessing(__dirname, 2).toString() +imgLocation).replace(/\\/g, '/');
        imgObj.imgLocation=imgLocation;
        imgLocation_arr .push(imgObj)
      }
      res.json(imgLocation_arr )

    });
    pool.releaseConnection(conn); // 释放连接池,等待别的连接使用
  });
});

module.exports = router;

顺带一提,可以直接用res.sendFile(相对此文件的相对路径(更深的),{root:__dirname}来返回图片 能用成功了,但是这样写好像只能返回一张,我没能返回一组。找个时间试试看返回一组。

postman测试结果

在这里插入图片描述

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先需要安装依赖: ```bash npm install vue element-ui axios express multer ``` 其中,axios用于发送HTTP请求,express和multer用于处理后端的文件上传。 在前端Vue组件中,需要引入element-ui的Upload组件,并监听其change事件,当用户选择文件后,调用axios发送POST请求将文件上传到后端: ```html <template> <div> <el-upload class="upload-demo" action="http://localhost:3000/upload" :on-change="handleUpload" :show-file-list="false" > <el-button size="small" type="primary">上传文件</el-button> </el-upload> </div> </template> <script> import axios from 'axios' export default { methods: { handleUpload(file) { const formData = new FormData() formData.append('file', file.raw) axios.post('http://localhost:3000/upload', formData).then(() => { this.$message.success('上传成功') }) } } } </script> ``` 在后端Node.js中,需要使用multer中间件处理文件上传,并创建一个路由来处理上传请求: ```javascript const express = require('express') const multer = require('multer') const app = express() const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, 'uploads') }, filename: function(req, file, cb) { cb(null, Date.now() + '-' + file.originalname) } }) const upload = multer({ storage: storage }) app.post('/upload', upload.single('file'), (req, res) => { res.send('上传成功') }) app.listen(3000, () => { console.log('Server running on port 3000') }) ``` 其中,multer中间件可以根据配置的storage来处理文件存储和命名,上述例子中将文件存储在uploads文件夹中,并以时间戳和原始文件名的组合作为文件名。在路由中,使用upload.single('file')来指定只上传单个文件,且文件名为file。最后,将上传成功的状态返回前端

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值