无法使用Spring REST控制器下载静态XML文件



这是我从Postman进行测试的代码段,获取文件内容,但我希望将文件作为打开窗口下载。

@Override
  public ResponseEntity<?> downloadXmlFile() {
    try {
       String FILE_PATH =new ClassPathResource(ApplicationConstants.my_xml).getFile().getPath();
       File file = new File(FILE_PATH);
       InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
         HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setContentDispositionFormData(file.getName(),file.getName());
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
         return new ResponseEntity<InputStreamResource>(resource,headers, HttpStatus.OK);
    } catch (Exception e) {
      LOG.error("Unexpected Exception occurred while serving the request" + e.getMessage());
      return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new BaseResponse(AccredoStatusCode.INTERNAL_SERVER_ERROR));
    }
  }

为什么我要下载文件内容而不是XML文件?

我在下面使用,它对我有用。

public ResponseEntity<?> getFile(@PathVariable String fileName) {
        try {
            String filePath = new ClassPathResource(fileName+".xml").getFile().getPath();
            File file = new File(filePath);
            InputStream xmlFileInputStream = new FileInputStream(file);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            /*headers.setContentType(MediaType.APPLICATION_XML);
            String filename = fileName+".xml";
            headers.setContentDispositionFormData(filename, filename);
            headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");*/
            return ResponseEntity.ok().headers(headers)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(xmlFileInputStream));
        }

最新更新