Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create structured archive with files in java

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading