这是我的代码片段,当我从邮递员测试它,获取文件内容,但我希望文件下载为打开窗口。
@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文件?
答案 0 :(得分:0)
我在下面使用过,它对我有用。
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));
}