Search code examples
javarestspring-bootzip

How to ZIP the downloaded file using spring boot


I am beginner in java and would like some assistance with zipping a downloaded file using rest api call to MSSQL backend. Below is the code snippet which takes the ID as input parameter, fetches the record specific for that ID and downloads it locally. I now need the code modified to Zip the file when it is downloading.

@GetMapping("/message/save")
    @CrossOrigin(origins = "*")
    public ResponseEntity<byte[]> download(@RequestParam("id") Long id) throws Exception {
        Optional<MessageEntity> messageRecord = messageRepository.findById(id);
        MessageEntity messageEntity = messageRecord.get();
        ObjectMapper objectMapper = new ObjectMapper();
        String xml = objectMapper.writeValueAsString(messageEntity);
        byte[] isr = xml.getBytes();
        String fileName = "message.zip";
        HttpHeaders respHeaders = new HttpHeaders();
        respHeaders.setContentLength(isr.length);
        respHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);
    }

I expect the output to be a zipped file.


Solution

  • I'm not sure that I understood your problem clearly. But I assume that you need just make zip from string:

    @GetMapping("/message/save")
    @CrossOrigin(origins = "*")
    public void download(@RequestParam("id") Long id, HttpServletRequest request,
                         HttpServletResponse response) throws Exception {
        MessageEntity messageEntity = messageRepository.findById(id).orElseThrow(() -> new Exception("Not found!"));
        String xml = new ObjectMapper().writeValueAsString(messageEntity);
        String fileName = "message.zip";
        String xml_name = "message.xml";
        byte[] data = xml.getBytes();
        byte[] bytes;
        try (ByteOutputStream fout = new ByteOutputStream();
             ZipOutputStream zout = new ZipOutputStream(fout)) {
            zout.setLevel(1);
            ZipEntry ze = new ZipEntry(xml_name);
            ze.setSize(data.length);
            zout.putNextEntry(ze);
            zout.write(data);
            zout.closeEntry();
            bytes = fout.getBytes();
        }
        response.setContentType("application/zip");
        response.setContentLength(bytes.length);
        response.setHeader("Content-Disposition",
                "attachment; "
                        + String.format("filename*=" + StandardCharsets.UTF_8.name() + "''%s", fileName));
        ServletOutputStream outputStream = response.getOutputStream();
        FileCopyUtils.copy(bytes, outputStream);
        outputStream.close();
    }