zoukankan      html  css  js  c++  java
  • vue 利用axios请求接口下载excel

    一般有三种方法:

    方法一: 通过a标签下载

    // href为文件的存储路径或者地址,download为问文件名
    <a href="/images/download.jpg" download="downloadFileName" />
    

    优点:简单方便。
    缺点:这种下载方式只支持Firefox和Chrome不支持IE和Safari,兼容性不够好。

    方法二:通过window.location

    window.location = 'http://127.0.0.1:8080/api/download?name=xxx&type=xxx'
    

    优点:简单方便。
    缺点:只能进行get请求,当有token校验的时候不方便。

    方法三:通过请求后台接口

    // download.js
    import axios from 'axios'
    
    export function download(type, name) {
    axios({
        method: 'post',
        url: 'http://127.0.0.1:8080/api/download',
    // headers里面设置token
    headers: {
        loginCode: 'xxx',
        authorization: 'xxx'
    },
    data: {
        name: name,
        type: type
    },
    // 二进制流文件,一定要设置成blob,默认是json
    responseType: 'blob'
    }).then(res => {
        const link = document.createElement('a')
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', `${name}.xlsx`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    })
    }
    

      

  • 相关阅读:
    [Leetcode]-- Median of Two Sorted Arrays
    Implement strStr()
    [Leetcode]-- Remove Element
    3Sum
    推荐一个跨平台内存分配器
    ACE的缺陷
    详谈高性能UDP服务器的开发
    vi查找替换命令详解
    gcc多版本切换
    Centos 5.5升级Python到2.7版本
  • 原文地址:https://www.cnblogs.com/sllzhj/p/11672368.html
Copyright © 2011-2022 走看看