abh*_*han 7 rest spring-boot spring-rest
我可以下载单个文件,但如何下载包含多个文件的 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;
}
Run Code Online (Sandbox Code Playgroud)
这是我使用的工作代码 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
服务等级:-
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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用这些 Spring MVC 提供的抽象来避免将整个文件加载到内存中。
org.springframework.core.io.Resource
&org.springframework.core.io.InputStreamSource
这样,您的底层实现可以在不更改控制器接口的情况下进行更改,并且您的下载将逐字节流式传输。
请参阅此处接受的答案,该答案基本上用于org.springframework.core.io.FileSystemResource
创建Resource
zip 文件,并且也有一个动态创建 zip 文件的逻辑。
上面的答案的返回类型为 as void
,而您应该直接返回 aResource
或ResponseEntity<Resource>
。
如本答案所示,循环实际文件并放入 zip 流中。看看produces
和content-type
标题。
结合这两个答案即可得到您想要实现的目标。