![](/img/trans.png)
[英]Multiple zip file download on single Spring Boot rest controller
[英]Spring REST for zip file download
我正在使用從 UI 調用的以下 REST 方法來下載 ZIP 存檔:
@RequstMapping("/download")
public void downloadFiles(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_OK);
try {
downloadZip(response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException("Unable to download file");
}
}
private void downloadZip(OutputStream output) {
try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
byte[] bytes = getBytes();
zos.write(bytes);
zos.closeEntry();
} catch (Exception e) {
throw new RuntimeException("Error on zip creation");
}
}
它工作正常,但我想讓代碼更加面向 Spring,例如返回ResponceEntity<Resource>
而不是使用 Servlet API 的ServletOutputStream
。
問題是我找不到從ZipOutputStream
創建 Spring 資源的ZipOutputStream
。
ByteArrayResource或InputStreamResource?
這是一種返回字節流的方法,您也可以通過設置content-type來使用它返回zip文件。
@RequestMapping(value = "/download", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Resource> download() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
InputStream is = null; // get your input stream here
Resource resource = new InputStreamResource(is);
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.