我这里使用axios向后端发送ajax请求,并接收后端响应的二进制文件流,通过使用 response.data
创建了一个 Blob 对象,然后通过创建 URL.createObjectURL() 的链接,并将链接赋值给下载链接(a.href
)的 href 属性。最后触发 a.click()
事件来下载 blob 对象。
axios({
method: "get",
url: "http://localhost:8080/tool/gen/batchGenZip?param=user",
responseType: "blob", //收到的数据为blob
}).then(response =>{
const blob = new Blob([response.data], { type: response.headers["content-type"] });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");//创建一个a标签
a.href = url;// 设置超链接的地址
/*
后端设置的响应头,指定文件名和后缀名
response.setHeader("Content-Disposition", "attachment; filename=\"" + tableName + "-" + simpleDateFormat.format(new Date()) + ".zip\"");
后端这里已经指定文件类型,也可前端设置
*/
//通过后端设置的响应头,获取文件名:
const fileName= response.headers["content-disposition"].split(";")[1].split("=")[1];
//前端也可以设置下载文件的文件名:
a.download = fileName;
a.click();
}).catch(error => console.log(error))
通过上述代码就可通过浏览器下载文件
注意:使用不同的请求,些许代码会有变动,这里使用axios发送请求引入的axios-0.18.0.js文件,
在前端项目中也可以在终端使用命令
npm install axios
并引入axios:
import axios from 'axios'