0

I have the following method

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

}

Instead of returning Object I would like to return ResponseEntity<Resource> if it possible to return the file or ModelAndView("redirect:/") otherwise.

I tried:

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

But instead of redirection I got message that the file I am trying to download is corrupted. Summing up I would like to change method signature to:

public ResponseEntiry<Resource> downloadFile(@PathVariable String fileName)  
pshemek
  • 1,369
  • 4
  • 17
  • 33

1 Answers1

0

About your first question on returning the file through ResponseEntity is already answered here : Return file from Spring @Controller having OutputStream

Agreeing wwith @chrylis, as he suggested the best approch for you to take in case of an exception is to throw the exception and handle it in sprind @ControllerAdvice class using @ExceptionHandler method annotation.

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

Official Doc.

Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39