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