Spring 引导休息服务下载包含多个文件的 zip 文件

Spring boot rest service to download a zip file which contains multiple file

我可以下载单个文件,但我如何才能下载包含多个文件的 zip 文件。

下面是下载单个文件的代码,但我有多个文件要下载。任何帮助将不胜感激,因为我在过去 2 天一直坚持这个。

@GET
@Path("/download/{fname}/{ext}")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response  downloadFile(@PathParam("fname") String fileName,@PathParam("ext") String fileExt){
    File file = new File("C:/temp/"+fileName+"."+fileExt);
    ResponseBuilder rb = Response.ok(file);
    rb.header("Content-Disposition", "attachment; filename=" + file.getName());
    Response response = rb.build();
    return response;
}

使用这些 Spring MVC 提供的抽象来避免将整个文件加载到内存中。 org.springframework.core.io.Resource & org.springframework.core.io.InputStreamSource

这样,您的底层实现可以在不更改控制器接口的情况下进行更改,而且您的下载将逐字节流式传输。

查看已接受的答案 here,它基本上是使用 org.springframework.core.io.FileSystemResource 创建 Resource 并且也有动态创建 zip 文件的逻辑。

上面的答案 return 类型为 void,而您应该直接 return 一个 ResourceResponseEntity<Resource>

this answer 中所示,循环您的实际文件并放入 zip 流。看看 producescontent-type headers。

结合这两个答案来获得您想要实现的目标。

这是我使用过的工作代码 response.getOuptStream()

@RestController
public class DownloadFileController {

    @Autowired
    DownloadService service;

    @GetMapping("/downloadZip")
    public void downloadFile(HttpServletResponse response) {

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=download.zip");
        response.setStatus(HttpServletResponse.SC_OK);

        List<String> fileNames = service.getFileName();

        System.out.println("############# file size ###########" + fileNames.size());

        try (ZipOutputStream zippedOut = new ZipOutputStream(response.getOutputStream())) {
            for (String file : fileNames) {
                FileSystemResource resource = new FileSystemResource(file);

                ZipEntry e = new ZipEntry(resource.getFilename());
                // Configure the zip entry, the properties of the file
                e.setSize(resource.contentLength());
                e.setTime(System.currentTimeMillis());
                // etc.
                zippedOut.putNextEntry(e);
                // And the content of the resource:
                StreamUtils.copy(resource.getInputStream(), zippedOut);
                zippedOut.closeEntry();
            }
            zippedOut.finish();
        } catch (Exception e) {
            // Exception handling goes here
        }
    }
}

服务Class:-

public class DownloadServiceImpl implements DownloadService {

    @Autowired
    DownloadServiceDao repo;

    @Override
    public List<String> getFileName() {

        String[] fileName = { "C:\neon\FileTest\File1.xlsx", "C:\neon\FileTest\File2.xlsx", "C:\neon\FileTest\File3.xlsx" };

        List<String> fileList = new ArrayList<>(Arrays.asList(fileName));       
        return fileList;
    }
}
public void downloadSupportBundle(HttpServletResponse response){

      File file = new File("supportbundle.tar.gz");
      Path path = Paths.get(file.getAbsolutePath());
      logger.debug("__path {} - absolute Path{}", path.getFileName(),
            path.getRoot().toAbsolutePath());

      response.setContentType("application/octet-stream");
      response.setHeader("Content-Disposition", "attachment;filename=supportbundle.tar.gz");
      response.setStatus(HttpServletResponse.SC_OK);

      System.out.println("############# file name ###########" + file.getName());

      try (ZipOutputStream zippedOut = new ZipOutputStream(response.getOutputStream())) {

         FileSystemResource resource = new FileSystemResource(file);

         ZipEntry e = new ZipEntry(resource.getFilename());
         e.setSize(resource.contentLength());
         e.setTime(System.currentTimeMillis());
         zippedOut.putNextEntry(e);
         StreamUtils.copy(resource.getInputStream(), zippedOut);
         zippedOut.closeEntry();

         zippedOut.finish();
      } catch (Exception e) {
         
      }
}