关于 向Mysql 插入 Blob字段 转

来源:互联网 发布:android 电商app 源码 编辑:程序博客网 时间:2024/04/29 11:54
  

 

testblob.jsp

<%@ page contentType="text/html;charset=gb2312"%> <%@ page import="java.sql.*" %><%@ page import="java.util.*"%><%@ page import="java.text.*"%><%@ page import="java.io.*"%> <html ><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>test blob</title></head><body><%java.sql.Connection conn; java.lang.String strConn; Class.forName("org.gjt.mm.mysql.Driver").newInstance(); conn= java.sql.DriverManager.getConnection("jdbc:mysql://localhost/test","root",""); %>

<%

InputStream str=request.getInputStream();

out.print("<br> File size :"+str.available());

 String sql="insert into test(id,pic) values(?,?)"; PreparedStatement pstmt=conn.prepareStatement(sql); pstmt.setString(1,"1");pstmt.setBinaryStream(2,str,str.available()); pstmt.execute();

out.println("Success,You Have Insert an Image Successfully");pstmt.close();

%> <a href="readblob.jsp">查看图片</a><a href="postblob.html">返回</a></body></html>

 

readblob.jsp

<%@ page contentType="text/html;charset=gb2312"%> <%@ page import="java.sql.*, javax.sql.*" %><%@ page import="java.util.*"%><%@ page import="java.text.*"%><%@ page import="java.io.*"%> <html > <head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>Read Blob</title></head>

<body><% java.sql.Connection conn;ResultSet rs=null;Class.forName("org.gjt.mm.mysql.Driver").newInstance(); conn= java.sql.DriverManager.getConnection("jdbc:mysql://localhost/test","root",""); Statement stmt=conn.createStatement(); rs=stmt.executeQuery("select * from test where id='1'");

if(rs.next()){Blob b = rs.getBlob("pic");int size =(int)b.length();out.print(size);

InputStream in=b.getBinaryStream();byte[] by= new byte[size];response.setContentType("image/jpeg");

ServletOutputStream sos = response.getOutputStream();int bytesRead = 0;while ((bytesRead = in.read(by))!= -1){     sos.write(by, 0, bytesRead);}

in.close();sos.flush();}%></body></html>

注意 mysql的 blob 有 3种类型 一种是 blob 2的16次方(65536)才60多k 一种是 longblob2的32次方(4G) 还有一种是 textArea类型 2的16次方(65536)

注意哦否则只能插入 一半哦!!!!

textArea 时

##############################

response.setContentType("image/jpeg");

ServletOutputStream sos = response.getOutputStream();int bytesRead = 0;while ((bytesRead = in.read(by))!= -1){     sos.write(by, 0, bytesRead);}

 

换成

response.setContentType("text/html");

in.read(by);

out.print(new String(by));

就可以输出 到网页了

in.close();sos.flush();
原创粉丝点击