Spring/Spring Web 관련
파일 압축 후 HttpServletResponse로 내보내기
일상코딩
2021. 12. 19. 22:00
@RequestMapping(value = "/downloadZipFile.do")
public void downloadZipFile(@RequestParam("bbsId") String bbsId, @RequestParam("atchmnflId") String atchmnflId, HttpServletResponse response) {
String filePath = "C:/upload/bbs";
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename=\"allInOne.zip\"");
FileOutputStream fos = null;
ZipOutputStream zipOut = null;
FileInputStream fis = null;
try {
zipOut = new ZipOutputStream(response.getOutputStream());
// db 에서 게시물에 첨부된 모든 파일들을 List에 담기
List<CmmnNttAtflDtlVO> atchmnFileInfoList = bbsService.atchmnFlList(atchmnflId);
List<File> fileList = atchmnFileInfoList.stream().map(fileInfo -> {
return new File(filePath + "/" + fileInfo.getStreFileNm());
}).collect(Collectors.toList());
for(File file : fileList) {
zipOut.putNextEntry(new ZipEntry(file.getName()));
fis = new FileInputStream(file);
StreamUtils.copy(fis, zipOut);
fis.close();
zipOut.closeEntry();
}
zipOut.close();
} catch (IOException e) {
System.out.println(e.getMessage());
try { if(fis != null)fis.close(); } catch (IOException e1) {System.out.println(e1.getMessage());/*ignore*/}
try { if(zipOut != null)zipOut.closeEntry();} catch (IOException e2) {System.out.println(e2.getMessage());/*ignore*/}
try { if(zipOut != null)zipOut.close();} catch (IOException e3) {System.out.println(e3.getMessage());/*ignore*/}
try { if(fos != null)fos.close(); } catch (IOException e4) {System.out.println(e4.getMessage());/*ignore*/}
}
}
참고:
http://stackoverflow.com/questions/27952949/spring-rest-create-zip-file-and-send-it-to-the-client