简体   繁体   English

无法使用Spring Rest Controller下载静态xml文件

[英]unable to download the static xml file using spring Rest Controller

Here is my code snippet when i test it from postman, getting the file content but i am expecting file to be downloaded as opening window . 这是我从邮递员测试时得到的文件内容,这是我的代码片段,但我希望文件将作为打开窗口下载。

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

Why I am getting file content instead of xml file to be downloaded? 为什么我要下载文件内容而不是xml文件?

I used below , it is working for me. 我在下面使用过,它正在为我工​​作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM