axios 跨域 ( CORS ) 取得 spring boot 的圖片並顯示於 vue 前端
在 Spring boot 對於 axios 在 cors 與 csrf 的整合配置(總結) 應該瞭解如何跨域來解決資料取得的問題,至於 Axios 跨域取得的圖片要如何顯示在前端,下面就來實作看看。
- 在 spring boot 中撰寫取得圖片,記得要對它作 Base64 的編碼
/** * 供給 CORS 跨域的前端圖片顯示時需先用Base64加碼, 前端再用 <img :src="'data:image/jpeg;base64,'+userAvatar"> 顯示圖片 * @param imageType * @param filename * @return * @throws Exception */ @RequestMapping(value = "/auth/showpic/{imageType}/{filename}") public ResponseEntity<byte[]> showPic( @PathVariable String imageType, @PathVariable String filename ) throws Exception { Resource imgFile = resourceLoader.getResource("file:" + rootPath + "/fileUpload/" + imageType +"/"+ filename); byte[] bytes = StreamUtils.copyToByteArray(imgFile.getInputStream()); byte[] encodedBytes = Base64.getEncoder().encode(bytes); return ResponseEntity .ok() .body(encodedBytes); }
- 在前端使用 axios 向 spring boot 送一個取得圖片的要求
axios.get('/auth/showpic/avatar/admin.png').then({res=>this.userAvatar=res.data})
- 然後使用 vue 的語法,在 src 中的 url 要使用
'data:image/jpeg;base64,'+圖片名
, 這樣就可以顯示圖片了
<img :src="'data:image/jpeg;base64,'+userAvatar">
你必須 登入 才能發表評論。