Как мне вернуть tar.gz файл через http весной

#java #spring #spring-boot #http #spring-mvc

Вопрос:

Я использую apache compress для создания и сжатия нескольких файлов в tar.gz файл. Затем я пытаюсь создать конечную точку, с которой может связаться другое приложение, чтобы получить tar.gz файл.

Я перепробовал несколько различных методов, но, похоже, не могу получить желаемый результат. В настоящее время я могу вернуть сжатый файл как файл .gz, но он мне нужен как .tar.gz файл.

Мой метод контроллера выглядит так:

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

Ответ №1:

Примечание: Убедитесь, что вы 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']

}