博客
关于我
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/

    你可能感兴趣的文章
    Prometheus 配置详解
    查看>>
    Prometheus 采集器使用详解
    查看>>
    Prometheus 黑盒监控实战
    查看>>
    prometheus+alertmanager+grafana监控部署教程
    查看>>
    Prometheus+Grafana构建智能化Kubernetes监控系统实战
    查看>>
    Prometheus+SpringBoot应用监控全过程详解
    查看>>
    Prometheus+SpringBoot应用监控全过程详解
    查看>>
    prometheus安装
    查看>>
    Prometheus实战教程:监控Kafka消息
    查看>>
    Prometheus实战教程:监控mysql数据库
    查看>>
    Prometheus实战教程:监控Nginx状态
    查看>>
    prometheus常用exporter下载地址大全
    查看>>
    Prometheus快速搭建与监控Linux系统实战
    查看>>
    prometheus报警与恢复告警的格式
    查看>>
    Pytorch中安装 torch_geometric 详细图文操作(全)
    查看>>
    prometheus监控docker容器实战
    查看>>
    Prometheus监控k8s集群使用邮箱和微信告警!
    查看>>
    Prometheus监控mysq数据库实战
    查看>>
    prometheus监控nginx实战
    查看>>
    Prometheus监控redis数据库实战
    查看>>