【发布时间】: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 内容。没有按预期工作。