如何在Spring中通过http返回tar.gz文件



我使用apache compress来创建和压缩一些文件到tar.gz文件中。然后,我尝试创建另一个应用程序可以联系的端点,以便接收tar.gz文件。

我已经尝试了许多不同的方法,但我似乎无法得到所需的输出。目前我已经能够返回压缩文件作为。gz文件,但我需要它作为。tar.gz文件。

我的Controller方法看起来像:

public ResponseEntity<?> getBundle(){
BundleService bundleService = new BundleService();
List<File>fileList = new ArrayList<File>();
List<String> implementationIds = policyService.getImplementationIdListForBundle(EnvironmentType.DEV, PlatformEngineType.REGO);
List<PolicyImplementation> implementationList = policyService.getImplementationsForBundle(implementationIds);
fileList = bundleService.createImplementationFiles(implementationList);

bundleService.createTarBall(fileList);
File tarball = new File("./policyadmin/bundleDirectory/bundle.tar");
//File gzippedTarball = bundleService.gzipTarBall();
String gzippedLocation = tarball.getAbsolutePath() + ".gz";
//File gzippedFile = new File(gzippedLocation);
Resource tarResource = new FileSystemResource(tarball);
//bundleService.deleteTarball(tarball);
return new ResponseEntity<Object>(tarResource, HttpStatus.OK); //! If I return a File instead of a resource gives me No converter for [class java.io.File] with preset Content-Type 'null']
}

我也有下面的代码来处理请求:

//GET: Endpoint for OPA to retrieve on the fly gzipped tarball for Bundles
@ApiOperation(value = "Method to retrieve on the fly gzipped tarball for bundles", nickname = "getBundle", notes="", response = Resource.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Request for Bundle.tar.gz received", response = Resource.class),
@ApiResponse(code = 404, message = "Unable to find requested Bundle.tar.gz")
})
@GetMapping(value = "/policyadmin/bundle", produces= { "application/gzip" })
default ResponseEntity<?> getBundle(){
return new ResponseEntity<File>(HttpStatus.NOT_IMPLEMENTED);   
}

注意:请确保您的tar.gz文件

设置内容类型:

public ResponseEntity<?> getBundle(HttpServletResponse response){

// Your other code
response.setContentType("application/gzip");
response.setHeader("Content-Disposition", "attachment; filename="bundle.tar.gz"");

return new ResponseEntity<Object>(tarResource, HttpStatus.OK); //! If I return a File instead of a resource gives me No converter for [class java.io.File] with preset Content-Type 'null']
}