前后端下载excel文件(文件下载)

20 篇文章 0 订阅
5 篇文章 0 订阅

java后端

看一下文件放的位置
请添加图片描述

    public void downloadSFDTemplateExcel(HttpServletResponse response) {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/template/SFDTemplate.xlsx");
            //强制下载不打开
            response.setContentType("application/force-download");
            OutputStream out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("SFDTemplate.xlsx", "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
  • postman调用的展示

请添加图片描述






vue前端

前端api方法

import request from '@/utils/request'
const base_url = ''
const eds = '/thirdAdmin/sfd/api'

// 下载模板
export function downloadSFDTemplateExcel() {
  return request({
    url: base_url + eds + '/downloadSFDTemplateExcel',
    responseType: 'blob',
    method: 'get'
  })
}



vue方法代码

	//下载方法
	downloadSFDTemplate(){
		downloadSFDTemplateExcel().then((res)=>{
			console.log(res)
			const aLink = document.createElement('a');
			//Blob中的type有很多,这里是下载excel中的xlsx
		    const blob = new Blob([res],{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
		    aLink.href = URL.createObjectURL(blob);
		    aLink.setAttribute('download', "SFDTemplate.xlsx"); // 下载文件名称
		    document.body.appendChild(aLink);
		    aLink.click();
		    URL.revokeObjectURL(aLink.href); // 释放URL对象
		    document.body.removeChild(aLink);
		})
	},




补充:
1.Blob中类型有很多,本文只是下载excel,其他文件填写的
2.前端 接口的responseType设置成blob

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值