博客
关于我
vue使用axios接收后台返回的文件流下载文件
阅读量:509 次
发布时间:2019-03-07

本文共 1183 字,大约阅读时间需要 3 分钟。

后台接口返回数据处理

在实际项目中,我们经常需要通过后台接口获取数据并进行处理。以下是一种常见的技术实现方案,重点介绍了文件下载功能的实现方式。

axios fetch 实现

我们可以使用 axios 进行异步请求,以下是代码示例:

this.axios({    method: "get",    headers: {        "content-type": "application/json",        Authorization: "Bearer " + sessionStorage.getItem("access_token")    },    url: 'your_URL',    params: {'name':'Jack'},    responseType: "blob"}).then(function (res) {    // 处理 blob 数据    let blob = new Blob([res.data]);    let url = window.URL.createObjectURL(blob);        // 创建下载链接    let a = document.createElement("a");    a.href = url;    a.download = "表格.xlsx";    a.click();        // 释放 url    window.URL.revokeObjectURL(url);}).catch(function (res) {    console.log("error", res);});

注意事项

  • responseType 必须设置为 "blob":这一步非常关键。如果忘记设置 responseType 为 "blob",下载的文件可能会损坏,导致无法正常打开。

  • 文件处理流程:从接口返回的 blob 数据开始,创建 Blob 对象后,可以通过 window.URL.createObjectURL() 创建临时 url,用于操作文件。

  • 文件下载实现:通过创建一个 anchor 元素(<a>),设置其 href 为临时 url,并指定 download属性,用户点击后即可下载文件。

  • 实现效果

    通过上述方法,用户可以在浏览器中直接下载所需的文件,操作流程简洁易懂。该方法适用于需要将后台接口返回的二维数据(如 Excel 文件)直接展示给用户的场景。

    可扩展性

    该方案基于现代浏览器的 Blob API 实现,兼容性较高。需要注意的是,某些老旧浏览器可能不支持此方法,具体可根据项目需求进行适配。

    总结

    通过上述方法,我们可以轻松实现后台接口返回数据的文件下载功能。关键在于正确设置 responseType 和正确处理 blob 数据。

    转载地址:http://nuwnz.baihongyu.com/

    你可能感兴趣的文章
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>