一个向数据库存储数据image字段的jsp代码
发布时间:2023-05-13 15:14:18 所属栏目:教程 来源:
导读:我在程序代码里贴了向mysql数据库写入image代码的程序,可是好多人都是java的初学者,对于这段代码,他们无法将它转换成jsp,所以我在这在写一下用jsp怎样向数据库写入图像文件。大家先在数据库建这样一张表,我下面
我在程序代码里贴了向mysql数据库写入image代码的程序,可是好多人都是java的初学者,对于这段代码,他们无法将它转换成jsp,所以我在这在写一下用jsp怎样向数据库写入图像文件。大家先在数据库建这样一张表,我下面的这些代码对任何数据库都通用,只要支持blob类型的 只要大家将连接数据库的参数改一下就可以了。 sql>create table image(id int,content varchar(200),image blob); 如果在sqlserver2000的数据库中,可以将blob字段换为image类型,这在sqlserver2000中是新增的。 testimage.html文件内容如下: <html> <head> <title>image file </title> <meta http-equiv="content-type" content="text/html; charset=gb2312"> </head> <form method=post action="testimage.jsp"> <input type="text" name="content"><br> <input type="file" name="image"><br> <input type="submit"></form> <body> </body> </html> 我们在form的action里定义了一个动作testimage.jsp,它的内容如下: <%@ 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("org.gjt.mm.mysql.driver").newinstance(); string url="jdbc:mysql://localhost/mysql?user=root&password=&useunicode=true&characterencoding=8859_1"; //其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改 connection conn= drivermanager.getconnection(url); string content=request.getparameter("content"); string filename=request.getparameter("image"); fileinputstream str=new fileinputstream(filename); string sql="insert into test(id,content,image) values(1,?,?)"; preparedstatement pstmt=dbconn.conn.preparestatement(sql); pstmt.setstring(1,content); pstmt.setbinarystream(2,str,str.available()); pstmt.execute(); out.println("success,you have insert an image successfully"); %> 下面我写一个测试image输出的例子看我们上面程序写的对不对,testimageout.jsp的内容如下: <%@ 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("org.gjt.mm.mysql.driver").newinstance(); string url="jdbc:mysql://localhost/mysql?user=root&password=&useunicode=true&characterencoding=8859_1"; //其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改 connection conn= drivermanager.getconnection(url); string sql = "select image from test where id=1"; statement stmt=null; resultset rs=null; try{ stmt=conn.createstatement(); rs=stmt.executequery(sql); }catch(sqlexception e){} try { while(rs.next()) { res.setcontenttype("image/jpeg"); 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(); } } catch(exception e){system.out.println(e);} %> </body> </html> 你运行这个程序,你就会看到刚才你写入美丽的图片就会显示在你面前。怎么样,用jsp来试试。 这种方法把图片写到数据库中会使数据库在短时间内容量飞涨,会影响性能的,另外一种做法将图片存上传到服务器上, 在数据库里只存放图片的路径,这是一个很好的方法。我建议大家采取后面一种方法。 (编辑:聊城站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐