1、通过jsp、html上传图片到数据库
先在addProduct.jsp前面加上文件类型控件,
页面上显示
然后选择文件,提交给后端接口的doPost或service方法,获得输入流:
InputStream inputStream=null;
Part filePart = req.getPart("picture");
if(filePart!=null) {
System.out.println("file name :"+filePart.getName()+" size"+filePart.getSize()+" file type"+filePart.getContentType());
inputStream=filePart.getInputStream();
}
接着将对象、该输入流传给dao,存入数据库:
public int save(Connection con, Product product, InputStream inputStream) {
log.debug("saving product instance");
int flag = 0;
try {
String sql = "insert into Product(productname,productdescription,picture,price,"
+ "categoryid)values(?,?,?,?,?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, product.getProductName());
statement.setString(2, product.getProductDescription());
if(inputStream!=null)
statement.setBlob(3, inputStream);
statement.setDouble(4, product.getPrice());
statement.setInt(5, product.getCategoryID());
flag = statement.executeUpdate();
log.debug("save successful");
} catch (Exception re) {
log.error("save failed", re);
try {
throw re;
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
当flag>0,存入成功。
2、从数据库中取出blob类型并显示到页面中
这里面有点巧妙,直接在想要显示的img的src里面设置新的访问请求(/getImg),自动访问获取图片的servlet,并通过该serlet显示出来。
basePath在前面heade.jsp有,
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
这时会发送新的请求/getImg?id,在GetImgServlet里面
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
ProductDao dao = new ProductDao();
int id=0;
if(req.getParameter("id")!=null) {
id=Integer.parseInt(req.getParameter("id"));
System.out.println("id"+id);
}
byte[] imgById = dao.getImgById(conn, id);
if(imgById!=null) {
resp.setContentType("image/gif");
ServletOutputStream os = resp.getOutputStream();
os.write(imgById);
os.flush();
}
}
调用dao的通过对象id找到相应的图片的byte数组方法:
public byte[] getImgById(Connection con, int id) {
log.debug("finding picture by productId");
byte[] imgByte=null;
try {
String queryString = "select picture from Product where productId=?";
PreparedStatement statement = con.prepareStatement(queryString);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
while(resultSet.next()){
Blob blob =resultSet.getBlob("picture");
imgByte=blob.getBytes(1, (int)blob.length());
}
} catch (Exception re) {
log.error("find picture failed", re);
try {
throw re;
} catch (Exception e) {
e.printStackTrace();
}
}
return imgByte; }//end getImgById
在doGet()里
resp.setContentType("image/gif");
ServletOutputStream os = resp.getOutputStream();
os.write(imgById);
将该byte数组通过ServletOutputStream 显示给jsp/html页面。