首页 > 开发 > JSP > 正文

JSP初级教程之跟我学JSP(八)

2020-05-06 19:54:20
字体:
来源:转载
供稿:网友
第八章 Blob类型数据的存取和使用第一个Servlet—— 图片文件的操作

以下是我经过改编得到的jsp代码:
------------------------------upphoto.htm------------------------------------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
head>

<body>
上传图片:
<form name="form1" method="post" action="upphoto.jsp">
<input name="id" type="text">
(输入一个整数作为该图片的ID)<br>
<input size="50" name="file" type="file">
<br>
<input type="submit" name="Submit" value="提交">
</form>
<p> </p>
<p> </p>
显示图片:<br>
<br>
<form name="form2" method="post" action="showphoto.jsp">
<input type="text" name="vid">
(输入该图片的ID)<br>
<input type="submit" name="Submit2" value="提交">
</form>
</body>
</html>
---------------------------------------------------------------------------
upphoto.htm包括两个<form>,form1用于选择要存于数据库的图片;form2用于显示一张数据库里的图片。
-----------------------------upphoto.jsp----------------------------------
<%@ include file="include.inc"%>
<%@ page contentType="text/html;charset=gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
</head>

<body>
<%
int id=Integer.parseInt(request.getParameter("id"));
request.setCharacterEncoding("gb2312");
String f=request.getParameter("file");//得到路径,如:c:/d/e.jpg
String fpath=f.replaceFirst("////","////////");//把一个/变成两个/,即路径改成:c://d/e.jpg

Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
Class.forName(CLASSFORNAME);//载入驱动程式类别
con=DriverManager.getConnection(SERVANDDB);//建立数据库连接
con.setAutoCommit(false);
String sql="insert into blb(id,blob) values("+id+",empty_blob())";//数据库里那个表名叫blb,字段的名就叫blob
pstmt=con.prepareStatement(sql);//添加一条blob字段为空的记录,
pstmt.executeUpdate();
pstmt=null;
sql="select * from blb where id="+id+" for update";
pstmt=con.prepareStatement(sql);//查找刚刚添加的那条记录
rs=pstmt.executeQuery();
if (rs.next()) 
{
oracle.sql.BLOB osb = (oracle.sql.BLOB) rs.getBlob("blob");
//到数据库的输出流
OutputStream outStream = osb.getBinaryOutputStream();
//这里用一个文件模拟输入流
File file = new File(fpath);
InputStream inStream = new FileInputStream(file);
//将输入流写到输出流
byte[] b = new byte[osb.getBufferSize()];
int len = 0;
while ( (len = inStream.read(b)) != -1) 
{
outStream.write(b, 0, len);
}
//依次关闭(注意顺序)
inStream.close();
outStream.flush();
outStream.close();
con.commit();
rs.close();
pstmt.close();
con.close();

共3页上一页123下一页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表