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")

 

你可能感兴趣的:(SpringBoot)