filename=new String(filename.getBytes("8859_1"),"gb2312"); String detail=request.getParameter("txtmail"); detail=new String(detail.getBytes("8859_1"),"gb2312"); //获得所要显示图片的标题、存储路径、内容,并进行中文编码 FileInputStream str=new FileInputStream(filename); String sql="insert into picturenews(content,image,detail) values(?,?,?)"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1,content); pstmt.setBinaryStream(2,str,str.available()); pstmt.setString(3,detail); pstmt.execute(); //将数据存入数据库 out.println("Success,You Have Insert an Image Successfully"); %>
4、网页中动态显示图片
接下来我们要编程从数据库中取出图片,其代码如下所示。
<%@ page contentType="text/html;charset=gb2312"%> <%@ page import="java.sql.*" %> <%@ page import="java.util.*"%> <%@ page import="java.text.*"%> <%@ page import="java.io.*"%> <html> <body> <% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //加载驱动程序类 Connection con=DriverManager.getConnection("jdbc:odbc:denglu","sa","sa"); Statement stmt=con.createStatement(); ResultSet rs=null; //建立ResultSet(结果集)对象 int id= Integer.parseInt(request.getParameter("id")); //获得所要显示图片的编号id,并转换为整型 String sql = "select image from picturenews WHERE id="+id+""; //要执行查询的SQL语句 rs=stmt.executeQuery(sql); while(rs.next()) { ServletOutputStream sout = response.getOutputStream(); //图片输出的输出流 InputStream in = rs.getBinaryStream(1); byte b[] = new byte[0x7a120]; for(int i = in.read(b); i != -1;) { sout.write(b); //将缓冲区的输入输出到页面 in.read(b); } sout.flush(); //输入完毕,清除缓冲 sout.close(); } %> </body> </html>
将此文件保存为testimageout.jsp文件。下一步要做的工作就是使用HTML标记:
<IMG src="testimageout.jsp?id=<%=rs.getInt("id")%>" width=100 height=100>
取出所要显示的图片,其中id是所要取出图片的编号。本例中我们输出了第一个和最后一个图片信息,详细的程序代码如下所示。
<%@ page contentType="text/html;charset=gb2312"%> <%@ page import="java.sql.*" %> <html> <head> <title>动态显示数据库图片</title> </head> <body> <% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:denglu","sa","sa"); Statement stmt=con.createStatement(); String sql=new String(); sql= "select * from picturenews"; ResultSet rs=stmt.executeQuery(sql); rs.last(); //将指针移至最后一条记录 %>
上一篇:垃圾清理势在必行——Java垃圾收集算法
下一篇:解析:删除数据库中重复数据的两个方法
|