简介:springboot前后端分离项目,要实现文件下载功能。如果文件较大时采用后端直接下载,将文件采用zip压缩后以流的方式写入响应中,返回给浏览器,浏览器解析完成下载。
一:获取下载请求,调用实现,返回响应。
@ApiOperation(value = "", notes = "")
//@UserLoginToken
@GetMapping(value = "/downTaskResult")
@ResponseBody
public RestfulResult downLoadTaskRes(@RequestParam Long id, @RequestParam(required = false) String token,HttpServletResponse response){
RestfulResult restfulResult = new RestfulResult();
try {
Boolean flag=batchTaskService.downLoadTaskRes(id,response);
if (flag){
return null;
}
}catch (Exception e){
logger.error("批量任务结果下载!",e);
restfulResult = new RestfulResult(ResCode.ERROR.getCode(),ResCode.ERROR.getMessage());
}
return restfulResult;
}
二:具体service实现
@Override
public Boolean downLoadTaskRes(Long id, HttpServletResponse response) throws RequestException {
string result="";//具体路径,demo暂时写null
//判断文件是否存在
URL pathUrl=null;
Path path=null;
try {
pathUrl=new URL(result);
path=Paths.get(pathUrl.toURI());
}catch (Exception e){
throw new RequestException(ResCode.TASK_FILE_ERROR.getCode(),
ResCode.TASK_FILE_ERROR.getMessage());
}
if (!Files.exists(path)){
throw new RequestException(ResCode.TASK_FILE_ERROR.getCode(),
ResCode.TASK_FILE_ERROR.getMessage());
}
String filePath=path.toString();
//String filePath="/Users/jiaokc/Desktop/list_diff_data.json";
String fileRealName=filePath.substring(filePath.lastIndexOf("/")+1);
String fileName=fileRealName.substring(0,fileRealName.lastIndexOf("."));
//下载文件压缩返回。
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" +fileName+".zip");
response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
response.setHeader("Access-Control-Allow-Origin","*");
zipUtil(response,filePath,fileRealName);
return true;
}
三:文件边压缩边下载
/**
* 压缩文件边压缩边下载
* @param response
* @param filePath
* @param fileName
*/
private void zipUtil(HttpServletResponse response,String filePath,String fileName) {
//设置压缩流:直接写入response,实现边压缩边下载
ZipOutputStream zipos = null;
try {
zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩存储方法
zipos.setLevel(9);//设置压缩率9
} catch (Exception e) {
e.printStackTrace();
}
//将文件写入压缩流
DataOutputStream os = null;
File file = new File(filePath);
try {
//添加ZipEntry,并ZipEntry中写入文件流
zipos.putNextEntry(new ZipEntry(fileName));
os = new DataOutputStream(zipos);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer= new byte[1024];
int length = 0;
while((length = bis.read(buffer))!= -1){
os.write(buffer, 0, length);
}
bis.close();
zipos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
//关闭流
try {
os.flush();
os.close();
zipos.close();
} catch (IOException e) {
e.printStackTrace();
}
}