Spring boot HeaderWriterFilter переопределяет заголовок, созданный в контроллере - PullRequest
0 голосов
/ 02 октября 2018

Когда я добавляю заголовок к responseEntity в контроллере, он не добавляется в ответ.Я отлаживаю код, и когда он достигает «HeaderWriterFilter», он добавляет заголовок по умолчанию, но он не отслеживает того, который был добавлен в контроллер.

@RequestMapping(
        value = "/get-file",
        method = RequestMethod.GET
)
public ResponseEntity<Resource> download(Principal principal, Long fileId) throws IOException {
    if (principal == null) {
        throw new UsernameNotFoundException("User not found.");
    }

    try {
        User loggedInUser = ((LoggedInUserDetails) ((UsernamePasswordAuthenticationToken) principal).getPrincipal()).getLoggedInUser();

//            Get file
        File file = this.fileService.getById(loggedInUser, fileId);
        if (file == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }

//            Get file for download
        java.io.File physicalFile = new java.io.File(file.getUrl());
        if (file == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
        InputStreamResource resource = new InputStreamResource(new FileInputStream(physicalFile));

        HttpHeaders headers = new HttpHeaders();
        headers.add("test", "test.yaml");

        return ResponseEntity.ok()
        .headers(headers)
        .contentType(MediaType.parseMediaType("application/octet-stream"))
        .contentLength(physicalFile.length())
        .body(resource);
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
    }
    catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
    }
}

1 Ответ

0 голосов
/ 10 октября 2018

Проблема заключалась в отсутствии заголовка в WebSecurityConfig.Я решил проблему, добавив

configuration.setExposedHeaders(Arrays.asList("fileName"));

в CorsConfigurationSource.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...