方法一:
需要注意的是,不能直接将图片放到resource下,要放到resource的某个目录下才行,否则回报错
@GetMapping("/getImage")
public void getImage(HttpServletResponse response) throws IOException {
ClassPathResource classPathResource = new ClassPathResource("/image/1.png");
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
StreamUtils.copy(classPathResource.getInputStream(),response.getOutputStream());
}
方法二:
通过字节流返回数据
@GetMapping("/getImage2")
public ResponseEntity<byte[]> getImage2() throws IOException {
ClassPathResource classPathResource = new ClassPathResource("/image/1.png");
byte[] bytes = StreamUtils.copyToByteArray(classPathResource.getInputStream());
return ResponseEntity
.ok()
.contentType(MediaType.IMAGE_JPEG)
.body(bytes);
}
有个感想是,在某些情况下,数据的传输都同先转换为字节同,然后通过字节流将数据返回