在Spring MVC中上传图片

6

我正在使用Spring 4和Hibernate 4将图片上传到数据库并从中检索。 我已将multipart图像转换为字节数组并存储在数据库中。 我的问题是如何从数据库中检索该图像,并在JSP中显示字节数组,而不必将其存储在本地系统中。


最好将图像上传到“磁盘路径”中,而不是使用数据库。 - Santhosh
我已经看过了,但在我的情况下,我需要将其存储在数据库中,有什么解决方案吗? - Shaik Mujahid Ali
抱歉,我不熟悉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 - Santhosh
尝试并在此处发布特定问题。 - Santhosh
3个回答

4

由于您没有提及存储图像的数据库结构,因此我假设您正在使用 blob 数据类型进行存储。

第一部分: ControllerClass

从数据库中检索图像后,您需要使用 Base64.encode 对该图像进行编码,并将其映射到您的 jsp(使用 java.util.map)。

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

第二部分: 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;
}

在服务方法中,只需返回输入流到控制器。
在控制器中。
@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;       
}

现在只需将 admin/user/{id}/photo 或任何您希望在 中使用的字符串插入, 只要它们匹配,您就可以获得您的照片。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接