首先写个上传页面:upload.html
1<html>
2 <head>
3 <title>Welcome</title>
4 </head>
5 <body>
6 <form action="insert2.jsp" method="post">
7 图片名称<input type="text" name="name" size="80"><br>
8 文件<input type="file" name="file"><br>
9 <input type="submit" name="submit" value="提交">
10 </form>
11 <center>Welcome</center>
12 </body>
13</html>
14
然后写blob数据的输入程序(insert2.jsp)
1<%@ page language="java" contentType="text/html;charset=gb2312"%>
2<%@page import="java.sql.*"%>
3<%@page import="java.io.*"%>
4<%@page import="java.util.*"%>
5<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en">
6<html>
7<head>
8<title>BLOB</title>
9</head>
10<body bgcolor="#FFFFFF">
11<%
12String name=request.getParameter("name");
13String file=request.getParameter("file");
14Connection conn;
15String strConn;
16request.setCharacterEncoding("gb2312");
17try{
18out.print(file+"<br>");
19File files=new File(file); //定义一个file
20FileInputStream str=new FileInputStream(files);//文件流
21Class.forName("org.gjt.mm.mysql.Driver").newInstance();//注册MYSQL驱动
22conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/book","root","root");//数据库连接
23String sql="insert into sample(name,image) values(?,?)";
24PreparedStatement pstmt=conn.prepareStatement(sql)编;//预译
25pstmt.setString(1,name);
26pstmt.setBinaryStream(2,str,(int)files.length());
27try{
28 pstmt.executeUpdate();
29}
30catch(SQLException e){
31 out.print(e.getMessage());
32}
33pstmt.close();
34conn.close();
35
36out.print("111111");
37}
38 catch(SQLException e){
39 out.print(e.getMessage());
40}
41catch(IOException e){
42 out.print(e.getMessage());
43}
44%>
45<a href="readblob2.jsp?name=<%=name%>">查看图片</a>
46
47Write your content here
48asdfasdfasdfsadf
49</body>
50</html>
51
现在在写个readblob把写如数据库中的blob字段输出到浏览器中:(readblob2.jsp)
<%@ page language="java" %>
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title>Lomboz JSP</title>
</head>
<body bgcolor="#FFFFFF">
<%
String name=request.getParameter("name");
out.print(name+"<br>");
Connection conn;
String strConn;
ResultSet rs;
Statement stmt;
try{
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/book","root","root");
stmt=conn.createStatement();
String sql="select * from sample where name='"+name+"'";
rs=stmt.executeQuery(sql);
ServletOutputStream op = response.getOutputStream();
if(rs.next())
{
Blob b = rs.getBlob("image");
long size = b.length();
//out.print(size);
byte[] bs = b.getBytes(1,(int)size);
response.setContentType("image/jpeg");
response.reset();
op.write(bs);
op.flush();
op.close();
}
rs.close();
conn.close();
stmt.close();
}catch(SQLException e){
out.print(e.getMessage());
}
catch(IOException e){
out.print(e.getMessage());
}
%>
</body>
</html>
小时候家的对面有一座山,山的上面就是蓝天,所以总是幻想着有一天站到山顶用手摸一下蓝天……
posted on 2008-10-20 13:16
丫丫 阅读(904)
评论(0) 编辑 收藏 所属分类:
jsp 、
mysql