第一步:建立資料庫
create table test_img(
id number(4),
name varchar(20),
img long raw);
第二步:
<html><head><title>添加圖片</title></head>
<body>
添加圖片<br>
<form method="post" action="insertNews.jsp">
映像ID:<input name="id" size="10">
<br>
選擇映像:<input type="file" name="image">
<br>
<input type="submit" value="上傳" name="submit" size="25">
<input type="reset" value="清除" name="clear" size="25">
<br>
</form>
</body></html>
第三步:插入資料庫(InsertImg.jsp)
<%@ page language="java"%>
<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*"%>
<%@ page import="java.text.*"%>
<%@ page import="java.io.*"%>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@lubin:1521:b2bdb";
Connection con=DriverManager.getConnection(url,"demo","demo");
//插入資料庫
String sql="insert into test_img values (?,?,?)";
//擷取傳值ID
String id=request.getParameter("id");
//擷取image的路徑
String kk=request.getParameter("image");
//轉換成file格式
File filename=new File(kk);
//將檔案的長度讀出,並轉換成Long型
long l1=filename.length();
int l2=(int)l1;
//以流的格式賦值
FileInputStream fis=new FileInputStream(filename);
PreparedStatement ps =con.prepareStatement(sql);
ps.setString(1,id);
ps.setString(2,filename.getName());
ps.setBinaryStream(3,fis,l2);
ps.executeUpdate();
ps.close();
fis.close();