gpt4 book ai didi

java - 无法使用 spring Rest Controller 下载静态 xml 文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:49:14 25 4
gpt4 key购买 nike

这是我从 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));
}

关于java - 无法使用 spring Rest Controller 下载静态 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48023196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com