简体   繁体   English

如何 ZIP 使用 spring 引导下载的文件

[英]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.我是 java 的初学者,希望在使用 rest api 调用 MSSQL 后端压缩下载的文件方面得到一些帮助。 Below is the code snippet which takes the ID as input parameter, fetches the record specific for that ID and downloads it locally.下面的代码片段将 ID 作为输入参数,获取特定于该 ID 的记录并将其下载到本地。 I now need the code modified to Zip the file when it is downloading.我现在需要在下载文件时将代码修改为 Zip 文件。

@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.我希望 output 是一个压缩文件。

I'm not sure that I understood your problem clearly.我不确定我是否清楚地理解了您的问题。 But I assume that you need just make zip from string:但我假设你只需要从字符串中制作 zip :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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