繁体   English   中英

用于 zip 文件下载的 Spring REST

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM