SpringBoot中接口返回圖片以及動態(tài)設置Content-type的寫法

使用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接口的定義。

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容