一個向數據庫存取image文件的jsp程序
2024-09-05 00:20:29
供稿:網友
我在程序代碼里貼了向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來試試。
這種方法把圖片寫到數據庫中會使數據庫在短時間內容量飛漲,會影響性能的,另外一種做法將圖片存上傳到服務器上,
在數據庫里只存放圖片的路徑,這是一個很好的方法。我建議大家采取后面一種方法。