java后台返回文件流下载文件,监听文件下载结束,实现下载前提示,文件传输完后关闭提示框效果!

java处理一般的文件下载都是直接文件流,可以达到浏览器自动弹出下载窗口的效果,如果是文件比较大或者后台处理逻辑用时比较长,为了页面更加友好,需要添加“遮罩层友情提示”,主要问题就是监听到文件传输完毕,此时需要使用fetch来实现,只改前台js即可,后台代码不用修改。

一般文件下载js代码:

点击按钮触发

function downLoadZip(){
    var url = "<%=basePath%>****downLoadZip.action";	
}

现实友情提示效果代码:

function downLoadZip(){
    //打开提示框
		layer.msg("后台正在生成打包中...",{
					icon:16,
					shade: [0.5, '#f5f5f5'],
					time:-1
				});
	var url = "<%=basePath%>********downLoadZip.action";	
	fetch(url, {
	method: 'GET',
	headers: {'Content-Type': 'application/json'},
	//body: '<请求参数:json字符串>',
}).then(res => res.blob()).then(data => {
	var blobUrl = window.URL.createObjectURL(data);
	downloads(blobUrl);
});
		}
		

function downloads(blobUrl) {
    //关闭提示框
    layer.closeAll();
	const a = document.createElement('a');
	a.style.display = 'none';
	a.download = '****报名登记表.zip';
	a.href = blobUrl;
	a.click();
	document.body.removeChild(a);
}

后台方法保持不变:

public void downLoadZip() throws Exception {
		//系统逻辑处理 。。。。。。
        //生成pdf 压缩zip 
		downLoadFile("***", "***.zip");

	}
public void downLoadFile(String pathdir, String fileName) throws IOException {

		String realpathdir = ServletActionContext.getRequest().getSession()
				.getServletContext().getRealPath(pathdir + fileName);

		HttpServletResponse response = (HttpServletResponse) ServletActionContext
				.getResponse();

		response.setContentType("application/zip");
		response.setHeader("Content-disposition", "attachment;filename="
				+ new String("*****报名登记表.zip".getBytes("gb2312"),
						"ISO8859-1"));
		File file = new File(realpathdir);

		ServletOutputStream sops = response.getOutputStream();
		FileInputStream fis = new FileInputStream(file);
		copyStream(fis, sops, true);
		fis.close();
		sops.close();
		fis = null;
		sops = null;
		file = null;

	}
private final long copyStream(InputStream source, OutputStream dest,
			boolean flush) {
		int bytes;
		long total = 0l;
		byte[] buffer = new byte[2048];
		try {
			while ((bytes = source.read(buffer)) != -1) {
				if (bytes == 0) {
					bytes = source.read();
					if (bytes < 0)
						break;
					dest.write(bytes);
					if (flush)
						dest.flush();
					total += bytes;
				}
				dest.write(buffer, 0, bytes);
				if (flush)
					dest.flush();
				total += bytes;
			}

		} catch (IOException e) {
			 throw new RuntimeException("IOException caught while copying.",e);
		}
		return total;
	}

 

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值