java当metod返回ResponseEntry<Resource>抛出错误时,如何返回ModelandView?
我有以下方法
@GetMapping("/{fileName}")
public Object downloadFile(@PathVariable String fileName) {
// Load file from database
errors.clear();
DBFile dbFile;
try {
dbFile = dBFileStorageService.getFileByName(fileName);
} catch (MyFileNotFoundException ex) {
logger.info("File has not been found.");
errors.add(ex.getMessage());
return new ModelAndView("redirect:/");
}
logger.info("Delivering file");
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(dbFile.getFileType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
.body(new ByteArrayResource(dbFile.getData()));
}
如果可以返回文件,我想返回ResponseEntity<Resource>
,而不是返回Object,否则返回ModelAndView("redirect:/")
我试过:
HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/member/uploadImage");
return new ResponseEntity<>(headers,HttpStatus.FOUND);
但我没有重定向,而是收到一条消息,说我试图下载的文件已损坏。 总结一下,我想将方法签名更改为:
public ResponseEntiry<Resource> downloadFile(@PathVariable String fileName)
# 1 楼答案
关于通过ResponseEntity返回文件的第一个问题,这里已经回答了: Return file from Spring @Controller having OutputStream
同意wwith@chrylis,正如他所建议的,在发生异常时,最好的方法是抛出异常,并使用
@ExceptionHandler
方法注释在sprin@ControllerAdvice
类中处理它官方Doc