springboot+vue+axios实现本地文件(txt excel)下载

后端

说明:我是读取本地文件,从前端传过来文件名,然后通过后端把文件传给前端,前端页面点击“下载”按钮,然后实现下载功能。本文主要讲述java下载txt文本,excel代码基本差不多,网上很多下载excel都是在后端代码中写好表头,我这个可以直接把做好的excel表格,通过流传给前端,下载。

java下载excel表格和txt文本,后端基本一样。前端有一点区别,下面会标注。

@GetMapping("/download/{fileName}")
public void download(@PathVariable(“fileName”) String fileName,
HttpServletRequest request, HttpServletResponse resp) throws IOException {
FileInputStream fis = null;
try {
String filePath =“C:/servicelogs/”+fileName;
fis = new FileInputStream(filePath);
resp.setContentType(“application/vnd.ms-excel;charset=UTF-8”);
resp.setCharacterEncoding(“UTF-8”);
resp.setHeader(“Content-Disposition”,
“attachment;filename=” + java.net.URLEncoder.encode(fileName, “UTF-8”));
byte[] b = new byte[100];
int len;
while ((len = fis.read(b)) > 0) {
resp.getOutputStream().write(b, 0, len);
}
} catch (Exception e) {
logger.error(“文件[ {} ]下载错误”, fileName);
} finally {
resp.getOutputStream().flush();
resp.getOutputStream().close();
fis.close();
}
}

前端

前端是用的vue elementui

downloadLog(index,row){
let filename=row.fileName;
this.$axios({
method:“get”,
url:"/onlinecar/log/download/"+filename,
headers: {‘Authentication’: store.state.account.token},
responseType: ‘blob’, //接收类型设置,否则返回字符型
data: this.qs.stringify({
fileName:filename,
})
}).then((res)=>{
let data=res.data;
if (!data){
return;
}
const blob=new Blob([data])

//下面注释 的这个代码是下载excel表格要加的东西,其他的excel txt是一样的
// const blob=new Blob([data],{
// type: “application/vnd.ms-excel” //type: “application/vnd.ms-excel” 这一句代码,是下载excel表格需要的,下载txt文件则//不需要这句,这是和下载txt文件 前端唯一的区别
// })

      if (window.navigator.msSaveOrOpenBlob){ // 兼容IE10
        navigator.msSaveBlob(blob,filename);
      }else { // 其他非IE内核支持H5的浏览器
        let url = window.URL.createObjectURL(blob);
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click()
      }
      
    }).catch((error)=>{
      this.$message.error(error);
    })
  },

这样就可以了,不懂评论问我

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值