使用SpringBoot的RestController来写接口后,不再使用httpServletResponse来操作请求的输出了,所以返回图片需要换一种方式
修改@RequestMapping
在RequestMapping / GetMapping新增produces属性,并把方法的返回值改为字节流byte[]类型:
@GetMapping(value = "/image",produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] getPicture() throws Exception {...}
实际逻辑的代码实现
public byte[] getPicture() throws Exception {
OutputStream out = null;
File file = new File("path/1.jpeg");
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
return bytes;
}
动态设置Content-type
如果逻辑中还需要实现鉴权 / 限流 / not found等报错;
分别让正常请求返回image/jpeg图片在异常时返回application/json错误信息,则可以如下改造:
@GetMapping("ct/{id}")
public ResponseEntity<Object> getPictureIfExist(@PathVariable Integer id) {
HttpHeaders headers = new HttpHeaders();
try {
//设置Content-type为image/jpeg
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
File file = new File("path/1.jpeg");
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
return new ResponseEntity<Object>(bytes, headers, HttpStatus.OK);
} catch (Exception e) {
//设置Content-type为application/json
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("code", 500);
resultMap.put("message", "not found");
return new ResponseEntity<Object>(resultMap, headers, HttpStatus.OK);
}
}
也就是不使用RequestMapping的produces参数,改用ResponseEntity的特性来灵活定义返回header的Content-type,借此实现RESTful接口的定义。