Home > Blockchain >  How do I return a tar.gz file via http in Spring
How do I return a tar.gz file via http in Spring

Time:10-22

I am using apache compress in order to create and compress a number of files into a tar.gz file. I am then attempting to create an endpoint that another application can contact in order to receive the tar.gz file.

I have tried a number of different methods but I cannot seem to get the desired output. Currently I have am able to return the compressed file as a .gz file but I need it as a .tar.gz file.

My Controller method looks like:

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']

    }

I also have the following code to handle the request:

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

CodePudding user response:

Note: Make sure you've tar.gz file

Set the content type like:

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']

}
  • Related