简体   繁体   English

在java中以zip下载多个文件(存储在数据库中)

[英]Download multiple files(stored in a database) in a zip in java

How to download multiple files in a zip folder.如何在一个 zip 文件夹中下载多个文件。 I am using spring-boot and documents are saved in MongoDB using GridFS.我正在使用 spring-boot,文档使用 GridFS 保存在 MongoDB 中。

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/我试图使用 FileSystemResource 下载,它将 File 作为参数并参考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我尝试使用下面的代码行从 mongodb 下载资源并将其转换为 File 对象

gridFsTemplate.getResource(GridFsFile).getFile();

I but it throws an error saying GridFS resource can not be resolved to an absolute file path.我但是它抛出一个错误,说GridFS 资源无法解析为绝对文件路径。

I have done using ByteArrayResource:我已经使用了 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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM