I want to implement GET api that returns ZIP file.
I defined api using openapi
openapi: 3.0.1
info:
title: xxx
description: xxx
version: 2.0.0
tags:
- name: xxxx
servers:
- url: /cc/api/v3
paths:
/path/{param}:
get:
tags:
- xxxx
operationId: getMyZip
responses:
200:
description: file with zipped reports
content:
application/octet-stream:
schema:
type: string
format: binary
security: []
As far as I understand my api should return byte[], so my controller looks like below
@Override
public ResponseEntity<Resource> getMyZip(String param) {
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new ByteArrayResource(myService.getMyZip(param)));
}
Is it ok to return byte[] or it should be some stream, end user will get the zip?
Implementation.
I have map of objects that I am parsing using Jackson object mapper.
How I could create folder structure and place files with json outputs from object mapper. Zip it and return to the caller.
Example:
myZip.zip
File1.json
File2.json
folder1
folder2
File3.json
Just use ZipOutputStream, and wrap it around a ByteArrayOutputStream:
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
ZipOutputStream zipStream = new ZipOutputStream(bStream);
ZipEntry myEntry = ZipEntry("my/awesome/folder/file.txt");
zipStream.addEntry(myEntry);
zipStream.write(myAwesomeData);
//add and write more entries
zipStream.close();
byte[] result = bStream.toByteArray();