JSP保存图片到数据库并显示出来
保存图片到数据库
<%
File file = new File("myimage.gif"
;
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps =
conn.prepareStatement("insert into images values (?,?)"
;
ps.setString(1,file.getName());
ps.setBinaryStream(2,fis,file.length());
ps.executeUpdate();
ps.close();
fis.close();
%>
显示图片
<img src=showimage.jsp?ID=1234>
...
=======================showimage.jsp=================
<%@ page language="java"
import="java.sql.*,java.util.*"%>
<%
String image_id = (String) request.getParameter("ID"
;
if (image_id != null){
try
{
Class.forName("oracle.jdbc.driver.OracleDriver"
;
Connection con = DriverManager.getConnection("jdbc
racle:thin:scott/tiger@www.myCompany.com:1243:myInstance","java","java"
;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM IMMAGINE WHERE IMMAGINE_ID = "
+ image_id);
if (rs.next())
{
String dim_image = rs.getString("IMMAGINE_DIMENSIONE"
;
byte [] blocco = rs.getBytes("IMMAGINE_IMMAGINE"
;
response.setContentType("image/jpeg"
;
ServletOutputStream op = response.getOutputStream();
for(int i=0;i<Integer.parseInt(dim_image);i++)
{
op.write(blocco
);
}
}
rs.close();
stmt.close();
con.close();
} catch(Exception e) {
out.println("An error occurs : "
+ e.toString());
}
}
%>