【vue3】vue3+express实现图片/pdf等资源文件的下载

文件资源的下载,是我们业务开发中常见的需求。作为前端开发,学习下如何自己使用node的express框架来实现资源的下载操作。

实现效果


代码实现

  • 前端

1.封装的请求后端下载接口的方法,需求配置aixos的请求参数里面的返回数据类型为blob

js 复制代码
// 下载
export function downLoad(name) {
  return instance.get(`/course/download?name=${name}`, {
    responseType: "blob",
  });
}

2.下载的核心方法,这里不能直接后端返回给我们的资源url,因为对于图片和pdf文件,浏览器的首选操作是预览,不是下载本地,所以我们这里需要转换下数据格式。

js 复制代码
const downloadSource = async (item) => {
  const data = await downLoad(item.attachments);
  const blob = new Blob([data]);
  let filename = item.name;
  const fileUrl = item.attachments;

  const extname = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
  filename = filename + "." + extname;

  const link = document.createElement("a");
  link.download = filename;
  link.target = "_blank";
  link.style.display = "none";
  link.href = URL.createObjectURL(blob);
  document.body.appendChild(link);
  link.click();
  URL.revokeObjectURL(link.href);
  document.body.removeChild(link);
};

3.后端响应的数据格式

  • 后端
    1.模拟数据

2.后端接口方法,"Content-Disposition这个响应头表示资源是需要下载的,如果含有中文可能会报错,解决方法是只需要我们encodeURIComponent转译就行了。

js 复制代码
//下载资料
const imagePath = (name) => path.join(__dirname, `../public/images/${name}`);
const downloadFile = (req, res, next) => {
  // console.log("🚀 ~ fs.readFile ~ imagePath:", req.query.name);
  const nameArr = req.query.name.split("/");
  fs.readFile(imagePath(nameArr[nameArr.length - 1]), (err, buffer) => {
    if (err) {
      res.status(500).send("Error reading image");
      return;
    }
    // 设置响应头
    switch (req.query.name) {
      case "pdf":
        res.setHeader("Content-Type", "application/pdf");
        break;
      default:
        res.setHeader("Content-Type", "image/jpeg");
    }

    // 设置响应头
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader(
      "Content-Disposition",
      `attachment; filename=${encodeURIComponent(nameArr[nameArr.length - 1])}`
    );

    // 发送图片数据
    res.send(buffer);
  });
};

3.配置请求方法路径

这样我们就实现了图片,pdf等资源的下载。这里只演示了图片和资源两种文件类型,其余的类型是一样的原理,可以自行添加测试。

相关推荐
十一.36637 分钟前
83-84 包装类,字符串的方法
前端·javascript·vue.js
over6971 小时前
深入解析:基于 Vue 3 与 DeepSeek API 构建流式大模型聊天应用的完整实现
前端·javascript·面试
接着奏乐接着舞1 小时前
react useMeno useCallback
前端·javascript·react.js
码农阿豪1 小时前
Vue项目构建中ESLint的“换行符战争”:从报错到优雅解决
前端·javascript·vue.js
韩曙亮2 小时前
【Web APIs】BOM 浏览器对象模型 ⑥ ( location 对象 | location 常用属性和方法 | URL 简介 )
前端·javascript·dom·url·bom·location·浏览器对象模型
春生野草2 小时前
Ruoyi前端基于vue的脚手架的目录解析
前端·javascript·vue.js
m0_740043733 小时前
Axios拦截器 -- 请求拦截器和响应拦截器
开发语言·前端·javascript
风止何安啊3 小时前
递归 VS 动态规划:从 “无限套娃计算器” 到 “积木式解题神器”
前端·javascript·算法
GPTMirrors镜像系统3 小时前
JS 实现指定 UA 访问网站跳转弹窗提醒,解决夸克等浏览器兼容性问题
前端·javascript
脾气有点小暴4 小时前
JavaScript 数据存储方法全解析:从基础到进阶
开发语言·javascript·ecmascript