关于java 往数据库插入图片的问题

2024-12-04 05:45:46
推荐回答(1个)
回答1:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//String htmlData = request.getParameter("content1");

Connection conn;
try {
conn = DataSourceFactory.getDataSource().getConnection();
String sql = "select diagram from blobtable where chapter_descr=?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, "testname");
ResultSet rs = pst.executeQuery();
rs.next();
BLOB blob = (BLOB)rs.getBlob("diagram");
InputStream bos = blob.getBinaryStream();
byte[] buf = new byte[blob.getBufferSize()];
int len;
while((len = bos.read(buf))>0){
response.getOutputStream().write(buf, 0, len);
}
} catch (SQLException e) {
e.printStackTrace();
}
// request.getRequestDispatcher("test.jsp").forward(request, response);

}

public static void insert() throws Exception {

Connection con = DataSourceFactory.getDataSource().getConnection();
con.setAutoCommit(false);//很关键,否则下面的update会抱错
PreparedStatement p = null;
p = con
.prepareStatement("INSERT INTO blobtable (chapter_descr,diagram_no,diagram)values(?,?,?)");
p.setString(1, "testname");
p.setInt(2, 27);
p.setBlob(3, BLOB.empty_lob());//此BLOB乃oracle.sql.BLOB类
p.executeUpdate();
p.close();
p = con
.prepareStatement("select diagram from blobtable where chapter_descr=? for update");
// select for update的好处是先锁住此行,防止并发问题
p.setString(1, "testname");
ResultSet rs = p.executeQuery();
rs.next();
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("diagram");
FileInputStream in = new FileInputStream(
"D:\\1.JPG");
OutputStream outB = blob.getBinaryOutputStream();
byte[] buf = new byte[blob.getBufferSize()];//缓冲的大小用这种方式获得性能最好
int len;
while ((len = in.read(buf)) > 0) {
outB.write(buf, 0, len);
}
outB.close();
in.close();
p.close();
p = con
.prepareStatement("update blobtable set diagram =? where chapter_descr=?");
p.setBlob(1, blob);
p.setString(2, "testname");
p.executeUpdate();
con.commit();
con.close();

}

public String showImg(String fileName) throws Exception{
Connection con;

con = DataSourceFactory.getDataSource().getConnection();

PreparedStatement p = null;

p = con
.prepareStatement("select diagram from blobtable where chapter_descr=?");
p.setString(1, "testname");
ResultSet rs = p.executeQuery();
rs.next();
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("diagram");
FileOutputStream out = new FileOutputStream(fileName);
InputStream bos = blob .getBinaryStream();

byte[] buf = new byte[blob.getBufferSize()];
int len;
while ((len = bos.read(buf)) > 0) {
out.write(buf, 0, len);
}
bos.close();
out.close();
p.close();

con.close();

return "";

}
}