2014-10-09 70 views
6

我使用spring 4和hibernate 4上傳圖像並從數據庫中檢索圖像。 我已經將多部分圖像轉換爲字節數組並存儲在數據庫中。 我的查詢是如何從數據庫中檢索該圖像,並在jsp中顯示字節數組而不將其存儲在本地系統中。在春天上傳圖像mvc

+0

斷章取義最好是將圖片上傳在'盤path',而使用的數據庫 – 2014-10-09 10:36:13

+0

我通過它去的,但在我的情況下,我需要將其存儲在數據庫,任何解決方案? – 2014-10-09 10:38:42

+0

對不起,我不熟悉hibernate。試試這個http://stackoverflow.com/questions/24567553/save-and-retrieve-image-from-database-using-spring-mvc-and-hibernate-rest-servic和http://stackoverflow.com/questions/17384928/hibernate-how-to-retrieve-an-image-from-the-database – 2014-10-09 10:41:34

回答

3

由於你沒有提到你的數據庫結構來存儲圖像,我會考慮你將它存儲在blob數據類型。

第1部分ControllerClass

從DB檢索圖像後,然後使用Base64.encode編碼圖像和(使用java.util.map),該圖像映射到你的jsp。

Map<String, Object> model = new HashMap<String, Object>(); 
model.put("myImage", Base64.encode(MyImage)); //MyImage (datatype 'byte[]') is the image retrieved from DB 
return new ModelAndView("display", model); //display is the name of jsp on which you want to display image 

第2部分JSP

然後由字節數組解碼其顯示在JSP

<img id="myImg" name="myImg" src="data:image/jpg;base64,<c:out value='${myImage}'/>" > 
0

字面上我們在做什麼是

在DAO方法

public InputStream get_user_photo_by_id(int id_user) throws Exception {  
    Blob blob_photo; 
    String sql = "Select b_photo_file from user_master where id_user = ?";      
blob_photo = getJdbcTemplate().queryForObject(sql, new Object[] {id_user}, Blob.class);  
    if(blob_photo!=null) 
     return blob_photo.getBinaryStream(); 
    else 
     return null; 
} 

在服務方法只是返回的InputStream控制器

在控制器

@ResponseBody 
@RequestMapping(value = "admin/user/{id}/photo", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) 
public byte[] testphoto(@PathVariable("id") int id_sys_user, HttpSession ses) throws Exception {   
    byte[] thumb = null; 
    InputStream in = UserOps.getUserPhotobyId(id_sys_user);  
    if(in!=null){ 
     thumb = IOUtils.toByteArray(in); 
    } 
    return thumb;  
} 

現在只需插入管理/用戶/ {ID} /照片或你想在< IMG SRC使用任何字符串=「」> 只要它們匹配,並且你得到了你的照片

0

你可以做到這一點沒有問題。您必須設置一個控制器,以便在瀏覽器請求時發送圖像。但是在這裏,控制器並沒有將它放在模型中來給它一個視圖,而是直接生成HTTP響應。然後在你的JSP中,你只需指出相關的URL。

這裏是它可能是什麼(部分)例如:

@RequestMapping(value = "/img/{imgid}") 
public void getFile(HttpServletRequest request, @PathVariable(value = "imgid") long imgid, HttpServletResponse response) throws IOException { 
    contentType = "img/png"; //or what you need 
    response.setContentType(contentType); 
    // find the image bytes into into byte[] imgBytes 
    response.setContentLength((int) imgBytes.length); 
    response.setStatus(HttpServletResponse.SC_OK); 
    OutputStream os = response.getOutputStream(); 
    os.write(imgBytes); 
}