如何使用spring从Mysql数据库中检索图像?
我将图片插入到Mysql数据库中,图片将被保存。如何使用spring从Mysql数据库中检索图像?
File file = new File("G:/photos/New Folder (2)/www.geocities.com_cliknenjoy_lakshmimittal.jpg");
byte[] bFile = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
inpatient.setImagefile(bFile);
我在mysql中使用blob数据类型。
private byte[] imagefile;
public byte[] getImagefile() {
return imagefile;
}
public void setImagefile(byte[] imagefile) {
this.imagefile = imagefile;
}
现在我无法从mysqldatabase打开图像文件,我该如何打开这一个?
如果使用JPA注解,你可以注释你的财产@Lob
@Lob
private byte[] imagefile;
也许还与@Basic(fetch=FetchType.LAZY)
,以避免数据的开销。
斯特凡诺
- 编辑
一旦你坚持的图像二进制内容作为一个byte [],你有两种方式来显示图像:写一个新的servlet或一个新的控制器。首先增加了不必要的复杂性,所以我通常使用第二种方法。
首先你必须选择控制器响应的路径;假设"/dbresources/images/{id}"
的控制器会像
@Controller
@RequestMapping(value = "/dbresources/images")
public class PictureImageController {
@Autowired
private PictureService pictureService; // a service to retrieve pictures fomr DB
// getters and setters
@RequestMapping(value = "/{id}")
public void writePicture(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
try{
Picture img = pictureService.findById(id);
response.setContent(picture.getImagefile());
response.setContentLength(picture.getImagefile().length);
//additionally, you should add the mime-type and the last
//change date (to allow the browsers to use the cache) if these info are available
response.getOutputStream().write(picture.getImagefile());
response.setStatus(HttpServletResponse.SC_OK);
}
catch(Exception e){
response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 404. Add specific catch for specific errors
}
}
然后在你的JSP(X),你需要编写
<img src="/dbresources/images/[the id of the image to show]" />
控制器将拦截这个请求,并会对其进行处理在输出流中写入图像的二进制内容。
希望这已经够清楚了。不要相信代码的正确性,因为我在飞行中写了它。
Stefano
**我使用这个注释,但我仍然得到该图像将显示[B @ 100271a像这样,我如何打开文件?“” – 2013-03-28 08:14:06
我不明白你在寻找什么。你的意思是,“我怎样才能从应用程序的GUI中以二进制表示的形式显示实际的图像?”。如果是这样,它是一个Web应用程序? – 2013-03-28 13:25:07
**亚当然,我想改变转换,如果有什么可能在web应用程序中显示gui模式?** – 2013-04-01 08:12:45
你是说你在使用Blob,但在你的例子中我可以看到byte []? – 2013-03-27 09:39:07
您尚未展示如何存储它或如何阅读它。 – 2013-03-27 14:16:07
雅我存储的字节[],但我会存储blob数据类型使用在MySQL中,我可以打开,看到从MySQL的图像。但我需要通过编码打开,图像显示从数据库。我怎样做? – 2013-03-28 08:17:46