Spring Boot Rest Service下载包含多个文件的zip文件

时间:2018-07-14 19:47:29

标签: rest spring-boot spring-rest

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

下面是下载单个文件的代码,但我要下载多个文件。过去两天来我一直坚持不懈,对此将不胜感激。

@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;
}

3 个答案:

答案 0 :(得分:3)

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

if exists (select * from TEP_Payments_Table where [Project Name] = 'test')
    select top 1 [Project Name] from TEP_Payments_Table where [Project Name] = 'test' order by payid desc
else
    select 'None'

公共类DownloadFileController {

@RestController

}

服务等级:-

公共类DownloadServiceImpl实现DownloadService {

@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
    }
}

答案 1 :(得分:0)

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

这样,您的底层实现可以更改而无需更改控制器接口,而且下载内容将逐字节传输。

请参阅已接受的答案here,该答案基本上是使用org.springframework.core.io.FileSystemResource创建Resource的,也有一种逻辑上可以即时创建zip文件的逻辑。

以上答案的返回类型为void,而您应直接返回ResourceResponseEntity<Resource>

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

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

答案 2 :(得分:0)

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) {
         
      }
}
相关问题