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

    你可能感兴趣的文章
    Struts2中使用Session的两种方法
    查看>>
    Stream API:filter、map和flatMap 的用法
    查看>>
    STM32工作笔记0032---编写跑马灯实验---寄存器版本
    查看>>
    Static--用法介绍
    查看>>
    ssm旅游信息管理系统的设计与实现bus56(程序+开题)
    查看>>
    order by rand()
    查看>>
    SSM(Spring+SpringMvc+Mybatis)整合开发笔记
    查看>>
    ViewHolder的改进写法
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>