0

I want to generate a password protected zip file and then return to frontend. I am using spring boot and zip4j library. Able to generate zip file in backend service,but not able to send to frontend.

Service

import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.EncryptionMethod;

public ZipFile downloadZipFileWithPassword(String password){
    
    String filePath="Sample.csv";
    
    ZipParameters zipParameters = new ZipParameters();
    zipParameters.setEncryptFiles(true);
    zipParameters.setCompressionLevel(CompressionLevel.HIGHER);
    zipParameters.setEncryptionMethod(EncryptionMethod.AES);
    ZipFile zipFile = new ZipFile("Test.zip", password.toCharArray());
    zipFile.addFile(new File(filePath), zipParameters);
    
    return zipFile;
}

Controller

import net.lingala.zip4j.ZipFile;

@GetMapping(value = "/v1/downloadZipFileWithPassword")
ResponseEntity<ZipFile> downloadZipFileWithPassword(@RequestParam("password")String password){
    
        ZipFile zipFile = service.downloadZipFileWithPassword(password);
        return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/zip"))
                .header("Content-Disposition", "attachment; filename=\"Test.zip\"")
                .body(zipFile);
    
} 

In controller How can I convert this ZipFile (net.lingala.zip4j.ZipFile) to outputstream and send it to client ?

  • Use the contructor of `ZipFile` using a `File`, then return the `File` instead of `ZipFile` and stream that to the client. – M. Deinum Mar 10 '22 at 08:22
  • @M.Deinum Thanks for your comment. I have no idea how to use the constructor of net.lingala.zip4j.ZipFile using java.io.File . Could you please write the code ? – user3332171 Mar 10 '22 at 09:37
  • You are now using the String based one, first create a `File` instead of `String`. – M. Deinum Mar 10 '22 at 09:38

1 Answers1

0

The below code worked for me.

import net.lingala.zip4j.ZipFile;

@GetMapping(value = "/v1/downloadZipFileWithPassword")
ResponseEntity<StreamingResponseBody> downloadZipFileWithPassword(@RequestParam("password") String password) {

    ZipFile zipFile = service.downloadZipFileWithPassword(password);
    return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/zip"))
        .header("Content-Disposition", "attachment; filename=\"Test.zip\"")
        .body(outputStream -> {

            try (OutputStream os = outputStream; InputStream inputStream = new FileInputStream(zipFile.getFile())) {
                IOUtils.copy(inputStream, os);
            }
        });

}