hibernate用clob存储word文件/所有类型文件 假设表TableName有3个字段 id --主键 fileName--文件名(包括扩展名) fileContent--文件内容(clob型) 用hibernate将clob映射为String型 <property name="fileContent" type="java.lang.String"> <column name="FILE_CONTENT" /> </property> 两个公用方法: /** * 将base64字符串解码后返回字节数组 */ public static byte[] getFromBASE64ToByte(String s) { if (s == null) return null; BASE64Decoder decoder = new BASE64Decoder(); try { byte[] b = decoder.decodeBuffer(s); return b; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将文件转换为BASE64加密字符串 * * @param file * @return */ public static String fileToString64(File file) { if (file != null) { BASE64Encoder encoder = new BASE64Encoder(); try { InputStream in = new FileInputStream(file); byte[] bt = new byte[in.available()]; in.read(bt); String cont = encoder.encode(bt); in.close(); return cont; } catch (Exception e) { e.printStackTrace(); return null; } } else { return null; } } 文件入库: TableName con=new TableName(); File file=new File("C:/test.doc"); con.setFileName(file.getName()); con.setFileContent(fileToString64(file));//将文件转换为BASE64加密字符串 service.save(con);//入库 获取数据库中的文件内容: TableName con=service.findById(id); FileOutputStream fos=new FileOutputStream("C:/ttt_"+con.getFileName()); fos.write(getFromBASE64ToByte(con.getFileContent()));//解码并写入文件 fos.close(); 该方法可保存任意类型文件,获取出来后不会乱码。 稍作修改就可变成文件上传下载: public String download(){//下载 try { Long id=Long.valueOf(request.getParameter("id")); if (id!=null&&id>0) { TableName con=service.findById(id); if (con!=null&&con.getFileContent()!=null) { String fileName=URLEncoder.encode(con.getFileName(),"UTF-8"); String doc=con.getFileContent(); response.setHeader("Content-Disposition", "attachment;filename="+ fileName.trim()); response.setContentType("application/octet-stream"); ServletOutputStream out = response.getOutputStream(); out.write(getFromBASE64ToByte(doc));//解码、写出 out.close(); } } } catch (Exception e) { } return null; }
|