1. 程式人生 > >SpringBoot介面返回圖片

SpringBoot介面返回圖片

  • 使用 ResponseEntity 返回結果,設定HttpHeader中的content-type,如:image/png
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity getFile(@RequestParam long id) {
        Result result = fileService.getFile(id);
        if (result.getCode() == 1) {
            MediaType mediaType = MediaType.parseMediaType(result.getMsg());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(mediaType);
            ResponseEntity e = new ResponseEntity(result.getData(), headers, HttpStatus.OK);
            return e;
        }
        return ResponseEntity.status(404).body(result.getMsg());
    }
  • 第二種方法:在@RequestMapping中加上 produces 來設定圖片型別, 不需要單獨設定HttpHeaders
@RequestMapping(method = RequestMethod.GET, produces = "image/png")