-2

path = uploads/files/38c84b59-101b-4606-8fe7-3328f1871c03.pdf

@RequestMapping(method = RequestMethod.GET, value = "/explorer/file/{id:.+}")
        @ResponseBody
        public ResponseEntity<?> getFile(@PathVariable Integer id) {
            String filename = explorerService.getById(id).getPath();
            try {
                return ResponseEntity.ok(resourceLoader.getResource("file:" + filename));
            } catch (Exception e) {
                return ResponseEntity.notFound().build();
            }
        }

instead of pdf it gives some text

Thanks a lot in advance

screenshot

M.T
  • 881
  • 2
  • 10
  • 17
  • 1
    Some text? What text? Care to elaborate about the issue – Balwinder Singh Aug 16 '16 at 04:13
  • You can go through this link: https://www.mkyong.com/spring/spring-resource-loader-with-getresource-example/ and http://stackoverflow.com/questions/32468057/loading-a-pdf-in-browser-from-a-file-in-the-server-file-system. Hope it will help you. – SkyWalker Aug 16 '16 at 04:35
  • maybe the `encoded` text is actually the `pdf` contents, try setting the `Content-Type:` – Scary Wombat Aug 16 '16 at 05:04
  • @ScaryWombat solved yeah encoded text was content of pdf file. i tried this method headers.setContentTy‌​pe(MediaType.parseMed‌​iaType("application/p‌​df")); and this worked for me – M.T Aug 16 '16 at 06:10

1 Answers1

2

Taking the comments from the main question into a formal answer. Important is that the browser is sending Accepts: */* or at least application/pdf or it will give an error on the request.

@RequestMapping(method = RequestMethod.GET, value = "/explorer/file/{id:.+}", produces = "application/pdf")
@ResponseBody
public ResponseEntity<?> getFile(@PathVariable Integer id) {
    String filename = explorerService.getById(id).getPath();
    try {
        return ResponseEntity.ok(resourceLoader.getResource("file:" + filename));
    } catch (Exception e) {
        return ResponseEntity.notFound().build();
    }
}
Shawn Clark
  • 3,330
  • 2
  • 18
  • 30
  • HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/pdf")); return new ResponseEntity<>(resourceLoader.getResource("file:" + filename), headers, HttpStatus.OK); you were right thanks – M.T Aug 16 '16 at 06:03