BloB类型就是以二进制的形式把图片保存到数据库中。包括:TinyBlob、Blob、MediumBlob、LongBlob,这几个类型之间的唯一区别是在存储文件的最大大小上不同。
LongBlob 最大 4G
根据title可以查询到需要显示的图片的记录,然后获取图片
这就完成了。总体思想是要想获取一张图片,必须要根据该图片的特征(就是我文中提到的title)在数据库中查找出有该图片的记录,然后再获取它在数据库中的二进制,最后用OutputStream形成图片。
那么如果全部查询(select * from found),想把每一张图片都显示在同一页面,又该怎么办?看下一篇文章。
TinyBlob 最大 255字节 ( 1024Byte(字节)=1KB )
Blob 最大 65KB
MediumBlob 中等16MLongBlob 最大 4G
我自己是以表单里选择上传文件的形式(图片也可以看作是一种文件)来把图片插入到数据库中的。
以下是代码:
public class Info {
private File photo;
private Date datetime;
public File getPhoto() {
return photo;
}
public void setPhoto(File photo) {
this.photo = photo;
}
public Date getDatetime() {
return datetime;
}
public void setDatetime(Date datetime) {
this.datetime = datetime;
}
public class infoDao {
//把Found数据放入到数据库中
public int InsertFound(Info info){
PreparedStatement pst=null;
int rs=0;
DBcoon coon=new DBcoon();
Connection coona=coon.getCoon();//连接数据库
String sql_insert="insert into found(title,name,photo,datetime) values (?,?,?,?)";//sql语句
try {
pst=coona.prepareStatement(sql_insert);
pst.setString(1, info.getTitle());
pst.setString(2, info.getName());
InputStream str=new FileInputStream(info.getPhoto());//把图片放进数据库中
long length=(long)str.available();//来获取文件的大小
pst.setBinaryStream(3, str, length);//public final void setBinaryStream(int parameterIndex,java.io.InputStream x,long length)
DateFormat mediumDateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM); //规定日期格式ʽ2005-8-8 9:17:42
String datetime=mediumDateFormat.format(new Date());// new Date()获取系统时间
pst.setString(4, datetime);
rs=pst.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
根据title可以查询到需要显示的图片的记录,然后获取图片
InputStream is=rst.getBinaryStream("photo");//rst就是结果集
session.setAttribute("rst",is);//把结果放到session中
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%
InputStream is = (InputStream)session.getAttribute("rst");
OutputStream os=null;
response.setContentType("text/html");
os = response.getOutputStream();
byte[] buffer=new byte[1024];//一次传的文件量
int len=0;
try {
while((len=is.read(buffer))>0){//读
os.write(buffer, 0, len);//写 (,起始位置,长度)
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //以下两行代码不可少,会显示不出图片 原因为 jsp中 response.getWriter()和response.getOutputStream()相互冲突
out.clear();
out=pageContext.pushBody();
%>
然后在你需要显示图片的页面中写
<img width="300" height="300" src="images.jsp">
这就完成了。总体思想是要想获取一张图片,必须要根据该图片的特征(就是我文中提到的title)在数据库中查找出有该图片的记录,然后再获取它在数据库中的二进制,最后用OutputStream形成图片。
那么如果全部查询(select * from found),想把每一张图片都显示在同一页面,又该怎么办?看下一篇文章。