【问题标题】:unable to download the static xml file using spring Rest Controller无法使用 spring Rest Controller 下载静态 xml 文件
【发布时间】:2017-12-29 13:14:33
【问题描述】:

这是我的代码 sn-p,当我从邮递员那里测试它时,获取文件内容,但我希望文件作为打开窗口下载。

@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 文件?

【问题讨论】:

  • 这里我没有使用 HttpserveletResponse 类
  • 你可以使用它。它不会改变您现有的任何功能
  • 您也可以将ContentDisposition 添加到httpHeaders。在 org.springframework.http.HttpHeaders 类的春季 5 中,您有方法 setContentDisposition(ContentDisposition contentDisposition)。在 Spring 4 中,您可以使用 set 方法。你可以这样做httpHeaders.set("Content-Disposition", "attachment; filename=" + file.getName());
  • 我使用了 httpHeaders.set("Content-Disposition", "attachment; filename=" + file.getName());在我的代码中,但仍然只是在响应中检索到 xml 内容。没有按预期工作。

标签: java xml spring rest


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多