首页 > 解决方案 > 当metod返回ResponseEntiry时如何返回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>如果可以返回文件或其他方式,我想返回而不是返回对象ModelAndView("redirect:/")

我试过:

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

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

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

标签: javaspring-bootthymeleafhttpresponse

解决方案


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

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

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

官方文档


推荐阅读