BLOB写入读出
BLOB入库 if (rs.next()) { //得到java.sql.Blob对象,然后Cast为oracle.sql.BLOB oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1).; //到数据库的输出流 OutputStream outStream = blob.getBinaryOutputStream(); //这里用一个文件模拟输入流 File file = new File("d:proxy.txt"); InputStream fin = new FileInputStream(file); //将输入流写到输出流 byte[] b = new byte[blob.getBufferSize()]; int len = 0; while ( (len = fin.read(b)) != -1) { outStream.write(b, 0, len); //blob.putBytes(1,b); } //依次关闭(注意顺序) fin.close(); outStream.flush(); outStream.close(); con.commit(); con.close(); BLOB出库 从数据库中读出BLOB数据没有上述由于连接池的不同带来的差异,只需要J2SE的标准类java.sql.Blob就可以取得输出流(注意区别java.sql.Blob和oracle.sql.BLOB)。代码如下: Connection con = ConnectionFactory.getConnection(); con.setAutoCommit(false); Statement st = con.createStatement(); //这里的SQL语句不再需要”for update” ResultSet rs = st.executeQuery( "select contents from BLOBIMG where id=103 "); if (rs.next()) { java.sql.Blob blob = rs.getBlob(1); InputStream ins = blob.getBinaryStream(); //用文件模拟输出流 File file = new File("d:output.txt"); OutputStream fout = new FileOutputStream(file); //下面将BLOB数据写入文件 byte[] b = new byte[1024]; int len = 0; while ( (len = ins.read(b)) != -1) { fout.write(b, 0, len); } //依次关闭 fout.close(); ins.close(); con.commit(); con.close(); 从JSP页面提交文件到数据库 (1) 提交页面的代码如下: (2) 由于JSP没有提供文件上传的处理能力,只有使用第三方的开发包。网络上开源的包有很多,我们这里选择Apache Jakarta的FileUpload,在http://jakarta.apache.org/commons/fileupload/index.html 可以得到下载包和完整的API文档。法奥为adajspException 处理页面(handle.jsp)的代码如下 <% boolean isMultipart = FileUpload.isMultipartContent(request); if (isMultipart) { // 建立一个新的Upload对象 DiskFileUpload upload = new DiskFileUpload(); // 设置上载文件的参数 //upload.setSizeThreshold(yourMaxMemorySize); //upload.setSizeMax(yourMaxRequestSize); String rootPath = getServletConfig().getServletContext().getRealPath("/") ; upload.setRepositoryPath(rootPath+"uploads"); // 分析request中的传来的文件流,返回Item的集合, // 轮询Items,如果不是表单域,就是一个文件对象。 List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); //如果是文件对象 if (!item.isFormField()) { //如果是文本文件,可以直接显示 //out.println(item.getString()); //将上载的文件写到服务器的WEB-INFwebstart下,文件名为test.txt //File uploadedFile = new File(rootPath+"uploadstest.txt"); //item.write(uploadedFile); //下面的代码是将文件入库(略): //注意输入流的获取 … InputStream uploadedStream = item.getInputStream(); … } 本文出自 51CTO.COM技术博客 |


sunlilei
博客统计信息
热门文章
最新评论
友情链接