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;
}