使用SpringBoot的RestController來寫接口后,不再使用httpServletResponse來操作請求的輸出了,所以返回圖片需要換一種方式
修改@RequestMapping
在RequestMapping / GetMapping新增produces屬性,并把方法的返回值改為字節(jié)流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;
}
動態(tài)設置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接口的定義。