java在后台设置response的文件流,在前台直接显示或者下载

发布于:2021-09-23 15:44:00

当在后台获取文件或者下载文件后需要在前台显示或者自动下载,可采用如下response流的方法实现


当设置response.setHeader(“Content-Disposition”, “attachment;fileName=”+fileName);的时候会直接下载,取消的时候会自动调到浏览器新窗口实现预览,然后手动下载
参数为response和文件全路径


private void responseFileStream(HttpServletResponse response, String filePath){
if(filePath.contains("%")){
try {
filePath = URLDecoder.decode(filePath,"UTF-8");
} catch (UnsupportedEncodingException e) {
}
}
if(filePath.contains("%")){
try {
filePath = URLDecoder.decode(filePath,"UTF-8");
} catch (UnsupportedEncodingException e) {
}
}

ServletOutputStream out = null;
FileInputStream in = null;
try {
in = new FileInputStream(new File(filePath));
String[] dir = filePath.split("/");
String fileName = dir[dir.length-1];
String[] array = fileName.split("[.]");
String fileType = array[array.length-1].toLowerCase();
//设置文件ContentType类型
if("jpg,jepg,gif,png".contains(fileType)){//图片类型
response.setContentType("image/"+fileType);
}else if("pdf".contains(fileType)){//pdf类型
response.setContentType("application/pdf");
}else{//自动判断下载文件类型
response.setContentType("multipart/form-data");
}
//设置文件头:最后一个参数是设置下载文件名
response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
out = response.getOutputStream();
// 读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} catch (FileNotFoundException e) {
} catch (Exception e) {
} finally {
try {
out.close();
in.close();
} catch (NullPointerException e) {
} catch (Exception e) {
}
}
}


controller:
我这里是先生成pdf,然后在前台下载


@GetMapping("/export")
@ApiOperationSupport(order = 8)
@ApiOperation(value = "导出pdf", notes = "传入recruitRequireList")
public void exportPdf(@ApiParam(value = "导出pdf", required = true) @RequestParam String ids, HttpServletResponse response) {
recruitRequireService.exportPdf(ids,response);
}

下载格式:

相关推荐

最新更新

猜你喜欢