简体   繁体   中英

Spring REST for zip file download

I'm using the following REST method to be called from the UI to download the ZIP archive:

    @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");
        }
    }

It's working fine, but I wanted to make the code more Spring oriented, eg to return ResponceEntity<Resource> instead of using ServletOutputStream of Servlet API.

The problem is that I couldn't find a way to create Spring resource from the ZipOutputStream .

ByteArrayResource或InputStreamResource?

Here is a way to return bytestream, you can use it to return zip file as well by setting content-type.

@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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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