下载附件问题
恶作剧 web
下载附件接口为get请求写入流中,中途失败会导致页面白屏
解决版本:后台失败重新设置响应头,前端根据响应内容判断是否成功
# 解决get请求下载附件白屏问题
/**
* 下载文件
*/
@GetMapping("/downFile")
public void downFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
//设置响应头
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
String fileName = URLEncoder.encode("业厅基本信息表", StandardCharsets.UTF_8.name());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
ServletOutputStream out = response.getOutputStream();
//写入输出流中
BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(Paths.get("filePath")));
byte[] buffer = new byte[bis.available()];
bis.read(buffer);
out.write(buffer);
out.flush();
out.close();
} catch (Exception e) {
log.error("downBusinessFile.error." + e.getMessage(), e);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
JSONObject jsonObject = new JSONObject();
jsonObject.put("success", false);
jsonObject.put("message", "下载文件异常");
response.getWriter().write(jsonObject);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$('.down_btn').on('click',function(event){
// 创建隐藏的 iframe 元素并设置 src 为下载地址
var iframe = $('<iframe>', {
src: "url",
style: 'display: none'
}).appendTo('body');
// 监听 iframe 加载完成事件
iframe.on('load', function () {
// 获取 iframe 内容
var content = iframe.contents().find('body').text();
// 解析 JSON 数据
var jsonData = JSON.parse(content);
// 处理 JSON 数据
console.log(jsonData);
if (!jsonData.success) {
alert(jsonData.message)
}
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22