互联网技术 · 2024年2月20日

Vue项目使用axios请求接口实现excel文件下载

本文实例为大家分享了Vue项目利用axios请求接口下载excel的具体代码,供大家参考,具体内容如下

据我了解的前端的下载方式有三种,第一种是通过a标签来进行下载,第二种时候通过window.location来下载,第三种是通过请求后台的接口来下载,今天就来记录一下这三种下载方式。

方法一: 通过a标签

// href为文件的存储路径或者地址,download为问文件名
<a href=”https://redspeed01.com/d/easyvpn24″ rel=”external nofollow” download=”logo” />

优点: 简单方便。

缺点: 这种下载方式只支持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=”https://redspeed01.com/d/easyvpn24″> link.setAttribute(download, `${name}.xlsx`)
 document.body.appendChild(link)
 link.click()
 document.body.removeChild(link)
 })
}

// download.java
@RequestMapping(value = “/api/download”,produces = “application/octet-stream”, method = RequestMethod.POST)
public void downloadTemplate(@RequestBody Map<String,Object> paramsMap, HttpServletResponse response) {
 try {
 if (paramsMap.get(“type”).equals(“xxx”) && paramsMap.get(“name”).equals(“xxx”)) {
  String[] str = new String[]{“区县”,”所属省份”,”所属地市”};
  Workbook workbook = ExportExcel.exportExcel(“行政区划表模版”, str, null, “yyyy-MM-dd”);
  download(response, workbook, “CityDict”);
 }
 } catch (Exception e) {
 e.printStackTrace();
 }
}

private void download(HttpServletResponse response, Workbook workbook, String fileName) {
 try {
 response.setContentType(“application/octet-stream;charset=UTF-8;”);
 response.addHeader(“Content-Disposition”, “attachment;fileName=” + fileName + “.xlsx”);
 ByteArrayOutputStream by = new ByteArrayOutputStream();
 OutputStream osOut = response.getOutputStream();
 // 将指定的字节写入此输出流
 workbook.write(osOut);
 // 刷新此输出流并强制将所有缓冲的输出字节被写出
 osOut.flush();
 // 关闭流
 osOut.close();
 } catch (IOException e) {
 LogUtils.getExceptionLogger().info(“下载模板错误:{}”, e.getMessage());
 }
}

优点: 可以在headers里面设置token,文件是java代码中生成的,生成的文件比较灵活。

缺点: 实现起来比较复杂。

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册