用于zip文件下载的Spring REST

时间:2018-03-02 11:14:59

标签: java spring spring-mvc download

我正在使用以下REST方法从UI调用以下载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资源的方法。

2 个答案:

答案 0 :(得分:0)

ByteArrayResource或InputStreamResource?

答案 1 :(得分:0)

这是一种返回字节流的方法,您可以通过设置内容类型来使用它来返回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);
}