java 將數據庫中的blob字段轉為圖片顯示在前端頁面上


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());
}


另一種寫法

@RequestMapping(value = "/showImage.do")
public void showImage(String id, HttpServletResponse response, HttpServletRequest request) throws IOException, SQLException {
User user=userService.getUserById(Integer.valueOf(id));
if(null != user){
//從數據庫讀取出二進制數據……
byte[] bb=user.getTp();
// 將圖像輸出到Servlet輸出流中。
ServletOutputStream sos = response.getOutputStream();
sos.write(bb, 0, bb.length);
sos.close();
}
// 禁止圖像緩存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
}
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM