gpt4 book ai didi

rest - Spring Boot Rest服务下载包含多个文件的zip文件

转载 作者:行者123 更新时间:2023-12-01 19:42:58 24 4
gpt4 key购买 nike

我可以下载单个文件,但如何下载包含多个文件的 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;
}

最佳答案

这是我使用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
}
}
}

服务等级:-

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

关于rest - Spring Boot Rest服务下载包含多个文件的zip文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51342844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com