[英]Spring REST - create ZIP file and send it to the client
I want to create a ZIP file that contains my archived files that I received from the backend, and then send this file to a user.我想创建一个 ZIP 文件,其中包含我从后端收到的存档文件,然后将此文件发送给用户。 For 2 days I have been looking for the answer and can't find proper solution, maybe you can help me :)
2天来我一直在寻找答案,但找不到合适的解决方案,也许你可以帮助我:)
For now, the code is like this (I know I shouldn't do it all in the Spring controller, but don't care about that, it is just for testing purposes, to find the way to make it works):现在,代码是这样的(我知道我不应该在 Spring 控制器中做所有的事情,但不要在意,它只是为了测试目的,找到让它工作的方法):
@RequestMapping(value = "/zip")
public byte[] zipFiles(HttpServletResponse response) throws IOException {
// Setting HTTP headers
response.setContentType("application/zip");
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
// Creating byteArray stream, make it bufferable and passing this buffer to ZipOutputStream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);
// Simple file list, just for tests
ArrayList<File> files = new ArrayList<>(2);
files.add(new File("README.md"));
// Packing files
for (File file : files) {
// New zip entry and copying InputStream with file to ZipOutputStream, after all closing streams
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
FileInputStream fileInputStream = new FileInputStream(file);
IOUtils.copy(fileInputStream, zipOutputStream);
fileInputStream.close();
zipOutputStream.closeEntry();
}
if (zipOutputStream != null) {
zipOutputStream.finish();
zipOutputStream.flush();
IOUtils.closeQuietly(zipOutputStream);
}
IOUtils.closeQuietly(bufferedOutputStream);
IOUtils.closeQuietly(byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
But the problem is, that using the code, when I enter the URL localhost:8080/zip
, I get a file test.zip.html
instead of .zip
file.但问题是,使用代码,当我输入 URL
localhost:8080/zip
时,我得到一个文件test.zip.html
而不是.zip
文件。
When I remove .html
extension and leave just test.zip
it opens correctly.当我删除
.html
扩展名并仅保留test.zip
时,它会正确打开。 So my questions are:所以我的问题是:
.html
extension?.html
扩展名? I have no idea what else can I do.我不知道我还能做什么。 I was also trying replace
ByteArrayOuputStream
with something like:我还尝试将
ByteArrayOuputStream
替换为:
OutputStream outputStream = response.getOutputStream();
and set the method to be void so it returns nothing, but It created .zip
file which was damaged?并将方法设置为无效,因此它不返回任何内容,但它创建了损坏的
.zip
文件?
On my MacBook after unpacking the test.zip
I was getting test.zip.cpgz
which was again giving me test.zip
file and so on.在我的 MacBook 上解压
test.zip
后,我得到了test.zip.cpgz
,它再次给了我test.zip
文件等等。
On Windows the .zip file was damaged as I said and couldn't even open it.正如我所说,在 Windows 上,.zip 文件已损坏,甚至无法打开。
I also suppose, that removing .html
extension automatically will be the best option, but how?我还认为,自动删除
.html
扩展名将是最好的选择,但是如何呢?
Hope it is no as hard as It seems to be :)希望它不像看起来那么难:)
Thanks谢谢
I replaced:我更换了:
response.setContentType("application/zip");
with:和:
@RequestMapping(value = "/zip", produces="application/zip")
And now I get a clear, beautiful .zip
file.现在我得到了一个清晰、漂亮的
.zip
文件。
If any of you have either better or faster proposition, or just want to give some advice, then go ahead, I am curious.如果你们中的任何人有更好或更快的提议,或者只是想提供一些建议,那么请继续,我很好奇。
@RequestMapping(value="/zip", produces="application/zip")
public void zipFiles(HttpServletResponse response) throws IOException {
//setting headers
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
// create a list to add files to be zipped
ArrayList<File> files = new ArrayList<>(2);
files.add(new File("README.md"));
// package files
for (File file : files) {
//new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
FileInputStream fileInputStream = new FileInputStream(file);
IOUtils.copy(fileInputStream, zipOutputStream);
fileInputStream.close();
zipOutputStream.closeEntry();
}
zipOutputStream.close();
}
@RequestMapping(value="/zip", produces="application/zip")
public ResponseEntity<StreamingResponseBody> zipFiles() {
return ResponseEntity
.ok()
.header("Content-Disposition", "attachment; filename=\"test.zip\"")
.body(out -> {
var zipOutputStream = new ZipOutputStream(out);
// create a list to add files to be zipped
ArrayList<File> files = new ArrayList<>(2);
files.add(new File("README.md"));
// package files
for (File file : files) {
//new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
FileInputStream fileInputStream = new FileInputStream(file);
IOUtils.copy(fileInputStream, zipOutputStream);
fileInputStream.close();
zipOutputStream.closeEntry();
}
zipOutputStream.close();
});
}
I am using REST Web Service
of Spring Boot
and I have designed the endpoints to always return ResponseEntity
whether it is JSON
or PDF
or ZIP
and I came up with the following solution which is partially inspired by denov's answer
in this question as well as another question where I learned how to convert ZipOutputStream
into byte[]
in order to feed it to ResponseEntity
as output of the endpoint.我正在使用
Spring Boot
的REST Web Service
,并且我将端点设计为始终返回ResponseEntity
,无论它是JSON
、 PDF
还是ZIP
,我想出了以下解决方案,该解决方案部分受到denov's answer
在这个问题和另一个问题中的回答的启发我在那里学习了如何将ZipOutputStream
转换为byte[]
以便将其作为端点的输出提供给ResponseEntity
。
Anyway, I created a simple utility class with two methods for pdf
and zip
file download无论如何,我创建了一个简单的实用程序类,有两种方法用于下载
pdf
和zip
文件
@Component
public class FileUtil {
public BinaryOutputWrapper prepDownloadAsPDF(String filename) throws IOException {
Path fileLocation = Paths.get(filename);
byte[] data = Files.readAllBytes(fileLocation);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String outputFilename = "output.pdf";
headers.setContentDispositionFormData(outputFilename, outputFilename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return new BinaryOutputWrapper(data, headers);
}
public BinaryOutputWrapper prepDownloadAsZIP(List<String> filenames) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/zip"));
String outputFilename = "output.zip";
headers.setContentDispositionFormData(outputFilename, outputFilename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteOutputStream);
for(String filename: filenames) {
File file = new File(filename);
zipOutputStream.putNextEntry(new ZipEntry(filename));
FileInputStream fileInputStream = new FileInputStream(file);
IOUtils.copy(fileInputStream, zipOutputStream);
fileInputStream.close();
zipOutputStream.closeEntry();
}
zipOutputStream.close();
return new BinaryOutputWrapper(byteOutputStream.toByteArray(), headers);
}
}
And now the endpoint can easily return ResponseEntity<?>
as shown below using the byte[]
data and custom headers that is specifically tailored for pdf
or zip
.现在,端点可以使用专门为
pdf
或zip
定制的byte[]
数据和自定义标头轻松返回ResponseEntity<?>
,如下所示。
@GetMapping("/somepath/pdf")
public ResponseEntity<?> generatePDF() {
BinaryOutputWrapper output = new BinaryOutputWrapper();
try {
String inputFile = "sample.pdf";
output = fileUtil.prepDownloadAsPDF(inputFile);
//or invoke prepDownloadAsZIP(...) with a list of filenames
} catch (IOException e) {
e.printStackTrace();
//Do something when exception is thrown
}
return new ResponseEntity<>(output.getData(), output.getHeaders(), HttpStatus.OK);
}
The BinaryOutputWrapper
is a simple immutable POJO
class I created with private byte[] data;
BinaryOutputWrapper
是一个简单的不可变POJO
类,我使用private byte[] data;
and org.springframework.http.HttpHeaders headers;
和
org.springframework.http.HttpHeaders headers;
as fields in order to return both data
and headers
from utility method.作为字段,以便从实用程序方法返回
data
和headers
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.