blob类型字段 文件下载

附件/文件下载功能 数据存储在数据库表中,字段类型blob

根据 pk_val 值查找到对应附件记录,T_MX_ATTACHMENT附件表
att_file 附件存储字段名 blob类型
//主要代码
public String downLoad(String guid, HttpServletRequest request,
HttpServletResponse response) {

	String finStr = "false";
	InputStream in = null;
	try{
		String sql = "select attachment_id,att_size,att_name,att_file from T_MX_ATTACHMENT where pk_val = ? ";//and att_name like '%"+filename+"%'
		List cxlist = hibernateDao.executeSqlQuery(sql, new Object[]{guid});
		for (int i = 0; i < cxlist.size(); i++) {
			Object[] ydArr = (Object[]) cxlist.get(0);
			String filename = ydArr[2].toString();
			long length = 0;
			if(ydArr[3]!=null){
				Blob blob = (Blob) ydArr[3];
				in = blob.getBinaryStream();
				length = blob.length();
			}
			
			// 设置response的编码方式
			response.setContentType("application/x-msdownload");
			// 写明要下载的文件的大小
			response.setContentLength((int) length);
			// 解决中文乱码
			response.setHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes("gbk"), "iso-8859-1"));//new String(filename.getBytes("utf-8"), "iso-8859-1"))
			// 读出文件到i/o流
			BufferedInputStream buff = new BufferedInputStream(in);
			byte[] b = new byte[1024];// 相当于我们的缓存
			long k = 0;// 该值用于计算当前实际下载了多少字节
			// 从response对象中得到输出流,准备下载
			OutputStream myout = response.getOutputStream();
			
			// 开始循环下载
			while (k < length) {
				int j = buff.read(b, 0, 1024);
				k += j;
				// 将b中的数据写到客户端的内存
				myout.write(b, 0, j);
			}
			// 将写入到客户端的内存的数据,刷新到磁盘
			myout.flush();
			myout.close();
			
		}
		finStr = "success";
	}catch (Exception e) {
		e.printStackTrace();
	}finally{
		if (in != null) {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	return finStr;
}
发布了10 篇原创文章 · 获赞 1 · 访问量 429

猜你喜欢

转载自blog.csdn.net/weixin_38919176/article/details/103242870