日期:2014-05-16  浏览次数:21044 次

文件存入MYSql表的blob

向MYSql的数据表中存入文件,这看似没有什么大问题,只要把文件存入longblob字段就行了。但是最近的实践发现看似简单的背后其实有很多陷阱。下面就来分享一下我遇到的问题及我的解决办法。

分类管理

先介绍一下我的应用,只有两个页面upload.jsp和download.jsp。upload.jsp使用common file upload来上传文件,并将文件存入mysql的数据表的longblob字段。download.jsp则是从数据库中取出该longblob字段的内容,并写到浏览器客户端。数据库的连接我选用tomcat的连接池,url为jdbc:mysql://localhost:3306/test?characterEncoding=gbk。jsp页面的编码都为gbk。数据表的结构如下

CREATE TABLE `file` (
		`id` int(11) NOT NULL AUTO_INCREMENT,
		`filename` varchar(255) CHARACTER SET utf8 NOT NULL,
		`content` longblob,
		`filetype` varchar(255) CHARACTER SET utf8 NOT NULL,
		`size` int(11) DEFAULT NULL,
		`ip` varchar(255) CHARACTER SET utf8 NOT NULL,
		`date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE 			CURRENT_TIMESTAMP,
		PRIMARY KEY (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=gbk 

?? 上传文件的java代码如下

request.setCharacterEncoding("gbk");
	if("POST".equalsIgnoreCase(request.getMethod())){
		DiskFileUpload upload = new DiskFileUpload();
		upload.setHeaderEncoding("gbk");
		List<FileItem> list = upload.parseRequest(request);
		
		for(FileItem fileItem : list){
			if(!fileItem.isFormField()){
				String filename = fileItem.getName().replace("\\", "/");
				filename = filename.substring(filename.lastIndexOf("/") + 1);
				
				Context envContext = (Context)new InitialContext().lookup("java:/comp/env");
				DataSource ds = (DataSource) envContext.lookup("mysqlTest");
				Connection conn = ds.getConnection();
				PreparedStatement preStmt = conn.prepareStatement("insert into file (filename, filetype, size, content, ip, date) values (?,?,?,?,?,?)");
				preStmt.setString(1, filename);
				preStmt.setString(2, fileItem.getContentType());
				preStmt.setInt(3, (int)fileItem.getSize());
				preStmt.setString(5, request.getRemoteAddr());
				preStmt.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
				preStmt.setBinaryStream(4, fileItem.getInputStream(),(int)fileItem.getSize());
				
				preStmt.executeUpdate();
				preStmt.close();
				conn.close();
			}
		}
	}

?

? 下载文件的代码如下

Context envContext = (Context)new InitialContext().lookup("java:/comp/env");
		DataSource ds = (DataSource) envContext.lookup("mysqlTest");
		conn = ds.getConnection();
		preStmt = conn.prepareStatement("select * from file where id = ?");
		preStmt.setInt(1, id);
		
		rs = preStmt.executeQuery();
		
		if(rs.next()){
			response.reset();
			response.setContentType(rs.getString("filetype"));
			response.setContentLength(rs.getInt("size"));
			
			InputStream ins = null;
			OutputStream ous = null;
			
			try{
				ins = rs.getBinaryStream("content");
				ous = response.getOutputStream();
				byte[] b = new byte[1024];
				int len = 0;
				while((len = ins.read(b))!= -1){
					ous.write(b, 0, len);
				}
			}finally{
				if(ous != null) ous.close();
				if(ins != null) ins.close();
			}

?

? 开始上传一些文本文件没问题,但是当上传的文件大于1M时就报出如下异常

com.mysql.jdbc.PacketTooBigException: Packet for query is too large (5553258 > 1048576). You can change this value on the server by setting the max_allowed_packet' variable.
	com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3279)
	com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1971)
	com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
	com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2625)
	com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
	com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
	com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
	com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
	org.apache.tomcat.dbcp.db