gpt4 book ai didi

java - 如何使用 spring boot 压缩下载的文件

转载 作者:行者123 更新时间:2023-12-01 22:18:09 25 4
gpt4 key购买 nike

我是 java 初学者,需要一些帮助来使用 MSSQL 后端的 REST API 调用来压缩下载的文件。下面的代码片段将 ID 作为输入参数,获取特定于该 ID 的记录并将其下载到本地。我现在需要修改代码以在下载文件时压缩文件。

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

我希望输出是一个压缩文件。

最佳答案

我不确定我是否清楚地理解了您的问题。但我假设您只需要从字符串制作 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();
}

关于java - 如何使用 spring boot 压缩下载的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58612084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com