how to convert byte array to zip file in SPring boot

Issue

I need to convert array byte to zip file. but my out put is a empty zip file. I don’t understand that.

I get help from here

my code is:

String resultBase64  = reportApplicationService.fetchReportExcel(...);

if (resultBase64 != null) {
    
    byte[] excel = base64.decode( resultBase64 );
    
    ZipInputStream z = new ZipInputStream(new ByteArrayInputStream(excel));
    int length;
    while ((length = z.read(excel)) > 0) {
        zip.write(excel, 0, length);
    }

    zip.closeEntry();
    zip.finish();
    z.close();

    zip.close();
    outputStream.flush();
    
    response.setHeader("Content-Disposition", "attachment; filename=name.zip");
    response.setContentType("application/zip");
    response.setContentLength((int) outputStream.size());
    StreamUtils.copy(new ByteArrayInputStream(outputStream.toByteArray()), response.getOutputStream());
    
}

the z.read(excel) is -1

thanks

Solution

I find it in here . I changed my code :

result = reportApplicationService.fetchReportExcel(id, periodId, compareId1, compareId2, branches);

if (result != null) {

    byte[] excel = base64.decode( result );

    ZipEntry entry = new ZipEntry("z.xls");
    entry.setSize(excel.length);
    zip.putNextEntry(entry);
    zip.write(excel);
    zip.closeEntry();

    zip.close();
    outputStream.flush();

    response.setHeader("Content-Disposition", "attachment; filename=name.zip");
    response.setContentType("application/zip");
    response.setContentLength((int) outputStream.size());
    StreamUtils.copy(new ByteArrayInputStream(outputStream.toByteArray()), response.getOutputStream());

}

create a file with z.xls name into name.zip.

Answered By – mehnet ali

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published