Oracle中插入图片并显示(用BLOB类型)(二)

2014-11-24 12:27:39 · 作者: · 浏览: 1
(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub

BlobDAO blobDAO = BlobDAO.getInstance();

byte[] bs = blobDAO.getImage("1");

try {

response.getOutputStream().write(bs);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}


添加图片到数据库

请在c盘下放入图片--c:\\4.gif

Java代码 收藏代码

public void savaImg(String imgId) {
//传的是存入数据库图片的id
initConn();
Statement st = null;
BLOB blob = null; //图片类型
OutputStream outputStream = null; //输出流
File file = null; //文件
InputStream inputStream = null; //输入流
ResultSet rs = null;
try {
conn.setAutoCommit(false); //事物由程序员操作
st = conn.createStatement();
st.executeQuery("insert into IMAGE_LOB values('"+ imgId +"',empty_blob())");
rs = st.executeQuery("select T_IMAGE from IMAGE_LOB where t_id='"+ imgId +"' for update");
if (rs.next()) {
blob = (BLOB) rs.getBlob(1);
outputStream = blob.getBinaryOutputStream();
file = new File("c:\\4.gif");
inputStream = new FileInputStream(file);
byte[] b = new byte[blob.getBufferSize()];
int len = 0;
while ((len = inputStream.read(b)) != -1) {
System.out.println(len);
outputStream.write(b, 0, len);
}
}

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
inputStream.close();
outputStream.flush();
outputStream.close();
rs.close();
st.close();
conn.commit();
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


操作完毕!

作者“669098238”