Download Zip file via HttpResponse Java

So, I grab a collection of blobs from the database (various mimetypes) and try to pin them for users to download via an HTTP response. I can download the download, but when I try to open the downloaded zip file, it says: "The archive is either in an unknown format or damaged." I tried the following code with the application / zip, application / octet-stream and application / x-zip-compression, but I'm starting to think that the problem is how I add files. I also use Java 7 and Grails 2.2.4.

Any help with this would be greatly appreciated. Thanks!

  final ZipOutputStream out = new ZipOutputStream(new FileOutputStream("test.zip"));


        for (Long id : ids){

            Object[] stream = inlineSamplesDataProvider.getAttachmentStream(id);


            if (stream) {

                String fileName = stream[0]
                String mimeType = (String) stream[1];
                InputStream inputStream = stream[2]
                byte[] byteStream = inputStream.getBytes();

                ZipEntry zipEntry = new ZipEntry(fileName)
                out.putNextEntry(zipEntry);
                out.write(byteStream, 0, byteStream.length);
                out.closeEntry();
            }
        }

        out.close();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + "test.zip" + "\"");
        response.setHeader("Content-Type", "application/zip");
        response.outputStream << out;
        response.outputstream.flush();
+4
source share
1 answer

: ZipOutputStream

, ZipOutputStream ByteArrayOutputStream []:

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final ZipOutputStream out = new ZipOutputStream(baos);

        Calendar cal = Calendar.getInstance();
        String date = new SimpleDateFormat("MMM-dd").format(cal.getTime());

        final String zipName = "COA_Images-" + date + ".zip";



        for (Long id : ids){

            Object[] stream = inlineSamplesDataProvider.getAttachmentStream(id);


            if (stream) {

                String fileName = stream[0]
                String mimeType = (String) stream[1];
                InputStream inputStream = stream[2];
                byte[] byteStream = inputStream.getBytes();

                ZipEntry zipEntry = new ZipEntry(fileName)
                out.putNextEntry(zipEntry);
                out.write(byteStream, 0, byteStream.length);
                out.closeEntry();
            }
        }

        out.close();

        response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + "\"");
        response.setHeader("Content-Type", "application/zip");
        response.getOutputStream().write(baos.toByteArray());
        response.flushBuffer();
        baos.close();

, !

+5

Source: https://habr.com/ru/post/1612327/


All Articles