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

猜你喜欢

转载自blog.csdn.net/zekeTao/article/details/85320048