后台返回文件流,监听文件下载结束

17 篇文章 0 订阅

1、后台正常返回流即可

@RequestMapping(value = "/download/fileword", method = RequestMethod.GET)
public void downLoad(HttpServletResponse response) {
        try (InputStream in = new FileInputStream(“G://test.docx”);){
            //String gFileName = URLEncoder.encode(fileName, "UTF-8");
            //如进行下载名为:文件(3).txt,下载时显示名为:文件+(3).txt --空格变为了+号
            //解决办法如下
            //String dFileName = gFileName.replaceAll("\\+", "%20");
            //设置输出的格式
            response.reset();	//去除前后空格
            //激活浏览器弹出窗口
            //response.setContentType("application/x-msdownload");
            //浏览器弹出窗口显示的文件名
            //response.addHeader("Content-Disposition", "attachment;filename="+dFileName);
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) > 0){
                response.getOutputStream().write(b, 0, len);
            }
           // File file = new File(WordText.fileNew);
           // file.delete();
        } catch (Exception e){
            e.printStackTrace();
        }

    }

2、前台js代码

var url = "http://192.168.15.127:8080/download/fileword”;
fetch(url, {
	method: 'GEt',
	headers: {'Content-Type': 'application/json'},
	//body: '<请求参数:json字符串>',
}).then(res => res.blob()).then(data => {
	alert("1112");
	var blobUrl = window.URL.createObjectURL(data);
	downloads(blobUrl);
});

function downloads(blobUrl) {
	const a = document.createElement('a');
	a.style.display = 'none';
	a.download = 'aa.docx';
	a.href = blobUrl;
	a.click();
	document.body.removeChild(a);
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值