java 將資料庫中的blob欄位轉為圖片顯示在前端頁面上
阿新 • • 發佈:2020-07-17
1.頁面寫法
$("#zdytp").attr("src",ApiUrl+"/abc/getpic?orgid=8020");
2.後臺寫法(引入提示jar包即可)
IOUtils 引入依賴
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
@RequestMapping(value = "/imageDisplay")public void imageDisplay(String orgid, HttpServletResponse response, HttpServletRequest request) throws IOException, SQLException {
HashMap<String,Object> map = service.getById(orgid);//從資料庫查詢這條記錄資訊
if (map != null && map.size() > 0) {
byte[] bytes = (byte[]) map.get("orglogo");//orglogo為blob大欄位 儲存kb資料
response.setContentType("image/jpeg, image/jpg, image/png, image/gif"); //設定輸出流內容格式為圖片格式
InputStream in1 = new ByteArrayInputStream(bytes); //將位元組流轉換為輸入流
IOUtils.copy(in1, response.getOutputStream());//將位元組從 InputStream複製到OutputStream中
}
String logoRealPathDir = request.getSession().getServletContext().getRealPath("/assets/images/icons.png");//獲取預設圖片路徑
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
InputStream is = new FileInputStream(logoRealPathDir);
IOUtils.copy(is, response.getOutputStream());
}