0

How to download multiple files in a zip folder. I am using spring-boot and documents are saved in MongoDB using GridFS.

I was trying to download using FileSystemResource which takes File as an argument taking reference from https://simplesolution.dev/spring-boot-download-multiple-files-as-zip-file/

I tried to get download a resource from mongodb using below line of code and convert it into File object using

gridFsTemplate.getResource(GridFsFile).getFile();

I but it throws an error saying GridFS resource can not be resolved to an absolute file path.

Bifrost
  • 417
  • 5
  • 23
  • 1
    Avoid using files altogether. You should somehow be able to retrieve the data from your database in the shape of a byte[] or ByteBuffer or some InputStream. You can write that to the zipOutputStream like in your example. – f1sh Jun 22 '22 at 11:10

1 Answers1

0

I have done using ByteArrayResource:

   public void downloadZipFile(HttpServletResponse response, List<String> listOfDocIds) {
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=download.zip");
        List<FileResponse> listOfFiles = myService.bulkDownload(listOfDocIds);// This call will fetch docs in the form of byte[] based on docIds.
        try(ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
            for(FileResponse fileName : listOfFiles) {
                ByteArrayResource fileSystemResource = new ByteArrayResource(fileName.getFileAsBytes);
                ZipEntry zipEntry = new ZipEntry(fileName.getFileName());
                zipEntry.setSize(fileSystemResource.contentLength());
                zipEntry.setTime(System.currentTimeMillis());

                zipOutputStream.putNextEntry(zipEntry);

                StreamUtils.copy(fileSystemResource.getInputStream(), zipOutputStream);
                zipOutputStream.closeEntry();
            }
            zipOutputStream.finish();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }


class FileResponse{
       private String fileName;
       private byte[] fileAsBytes;
       // setter and getters
    }
Bifrost
  • 417
  • 5
  • 23