gpt4 book ai didi

java - 当返回 ResponseEntity 的方法抛出错误时如何返回 ModelandView?

转载 作者:行者123 更新时间:2023-12-02 02:36:50 27 4
gpt4 key购买 nike

我有以下方法

@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()));

}

我不想返回 Object,而是想返回 ResponseEntity<Resource>是否可以返回文件或 ModelAndView("redirect:/")否则。

我尝试过:

HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/member/uploadImage");
return new ResponseEntity<>(headers,HttpStatus.FOUND);

但是我没有得到重定向,而是收到消息,表明我尝试下载的文件已损坏。总结一下,我想将方法​​签名更改为:

public ResponseEntiry<Resource> downloadFile(@PathVariable String fileName)  

最佳答案

关于通过 ResponseEntity 返回文件的第一个问题已在此处得到解答: Return file from Spring @Controller having OutputStream

同意 @chrylis,因为他建议您在发生异常时采取的最佳方法是抛出异常并使用 @ExceptionHandler< 在 sprint @ControllerAdvice 类中处理它 方法注释。

@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409 or according to your need any code
@ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex){
System.out.println("handling exception here!!!");
ModelAndView mv = new ModelAndView();
mv.setViewName("errorView");
mv.addObject("ERROR", "ERROR OCCURRED REDIRECTED "+ex.getMessage());
return mv;
}
}

官方Doc .

关于java - 当返回 ResponseEntity<Resource> 的方法抛出错误时如何返回 ModelandView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57199323/

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