首先说写入oracle的Blob字段

上一文章的实现方法没有贴出来,如下:

TempUserService.java

[html] view plaincopy
  1. package org.hd.tempuser.service;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.sql.Blob;
  5. import java.sql.SQLException;
  6. import java.util.List;
  7. import java.util.Map;
  8. import org.hd.tempuser.model.TempUser;
  9. import org.rd.framework.query.support.PaginationSupport;
  10. public interface TempUserService {
  11. public static final String BEAN_ID = "tempUserService";
  12. public List getTempUserList(Map queryParams,PaginationSupport paginationSupport);
  13. public TempUser getTempUserById(String tempuserid);
  14. public void delTempUserById(String tempuserid);
  15. public TempUser addTempUser(TempUser tempUser);
  16. public void editTempUser(TempUser tempUser);
  17. public void addTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum);
  18. public void editTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum);
  19. public void editTempUserWithoutBlob(TempUser tempUser,String loginUserJobNum);
  20. public void clearPhotoBlob(TempUser tempUser);
  21. }

TempUserServiceImpl.java

[java] view plaincopy
  1. package org.hd.tempuser.service.impl;
  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedOutputStream;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileNotFoundException;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.OutputStream;
  11. import java.sql.Blob;
  12. import java.sql.Connection;
  13. import java.sql.DriverManager;
  14. import java.sql.ResultSet;
  15. import java.sql.SQLException;
  16. import java.sql.Statement;
  17. import java.util.Date;
  18. import java.util.List;
  19. import java.util.Map;
  20. import oracle.sql.BLOB;
  21. import org.hd.tempuser.model.TempUser;
  22. import org.hd.tempuser.service.TempUserService;
  23. import org.hd.util.BlobUtil;
  24. import org.hibernate.Hibernate;
  25. import org.hibernate.LockMode;
  26. import org.hibernate.Session;
  27. import org.hibernate.Transaction;
  28. import org.hibernate.lob.SerializableBlob;
  29. import org.rd.framework.common.container.ContainerManager;
  30. import org.rd.framework.dao.impl.CommonServiceImpl;
  31. import org.rd.framework.keygen.IKeyGen;
  32. import org.rd.framework.query.support.PaginationSupport;
  33. import org.rd.framework.util.WebUtils;
  34. public class TempUserServiceImpl  extends CommonServiceImpl implements TempUserService{
  35. @Override
  36. public List getTempUserList(Map queryParams,
  37. PaginationSupport paginationSupport) {
  38. String qualificationString = WebUtils.getQualificationString(queryParams);
  39. String queryString = "select queryby from TempUser queryby" + qualificationString;
  40. String countString = "select count(queryby.hduid) from TempUser queryby" + qualificationString;
  41. paginationSupport.setTotalCount(count(countString));
  42. return find(queryString, paginationSupport);
  43. }
  44. public TempUser getTempUserById(String tempuserid){
  45. TempUser tempUser=null;
  46. String queryString = "select queryby from TempUser queryby  where queryby.hduid='"
  47. + tempuserid.trim()+"'";
  48. List list=find(queryString);
  49. if(list.size()>0){
  50. tempUser=(TempUser)list.get(0);
  51. }
  52. return tempUser;
  53. }
  54. public void delTempUserById(String tempuserid){
  55. TempUser tempUser=null;
  56. String queryString = "delete from hd_user queryby  where queryby.hduid='"
  57. + tempuserid.trim()+"'";
  58. if(tempuserid==null||tempuserid.equals("")){
  59. }else{
  60. createNativeSQL(queryString);
  61. }
  62. }
  63. public TempUser addTempUser(TempUser tempUser){
  64. IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
  65. .getComponent(IKeyGen.BEAN_ID);
  66. String Id = keyService.getUUIDKey();
  67. tempUser.setHduid(Id);
  68. //默认字段
  69. //      tempUser.setCreate_date(new Date());
  70. //      tempUser.setCreator(creator)
  71. create(tempUser);
  72. return tempUser;
  73. }
  74. public void editTempUser(TempUser tempUser){
  75. this.update(tempUser);
  76. }
  77. //此方法作废
  78. public void addTempUserTt(TempUser tempUser,Blob hbblob,String pathh){
  79. String serverLocalPath=BlobUtil.WEBCONTENT_PATH+pathh.replaceAll("/", "\\\\");
  80. IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
  81. .getComponent(IKeyGen.BEAN_ID);
  82. String Id = keyService.getUUIDKey();
  83. tempUser.setHduid(Id);
  84. Session s = null;
  85. byte[] buffer = new byte[1];
  86. buffer[0] = 1;
  87. try {
  88. s = this.getSessionFactory().openSession();
  89. Transaction tx = s.beginTransaction();
  90. s.save(tempUser);
  91. s.flush();
  92. s.refresh(tempUser, LockMode.UPGRADE);
  93. BLOB blob = (BLOB)hbblob;
  94. OutputStream out = blob.getBinaryOutputStream();
  95. //        String fileName = "oraclejdbc.jar";
  96. File f = new File(serverLocalPath);
  97. FileInputStream fin = new FileInputStream(f);
  98. int count = -1, total = 0;
  99. byte[] data = new byte[(int)fin.available()];
  100. fin.read(data);
  101. out.write(data);
  102. fin.close();
  103. out.close();
  104. s.flush();
  105. tx.commit();
  106. catch (Exception e){
  107. System.out.println(e.getMessage());
  108. finally {
  109. if (s != null);
  110. try {
  111. s.close();;
  112. catch (Exception e) {}
  113. }
  114. }
  115. //此方法作废
  116. public void addTempUserTtdd(TempUser tempUser,Blob hbblob,String pathh) throws SQLException, IOException, FileNotFoundException{
  117. String serverLocalPath=BlobUtil.WEBCONTENT_PATH+pathh.replaceAll("/", "\\\\");
  118. IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
  119. .getComponent(IKeyGen.BEAN_ID);
  120. String Id = keyService.getUUIDKey();
  121. tempUser.setHduid(Id);
  122. //得到数据库连接(驱动包是weblogic的,没有下载任何新版本)
  123. Connection con=null;
  124. ResultSet rs=null;
  125. InputStream in=null;
  126. BufferedInputStream bis=null;
  127. OutputStream os=null;
  128. BufferedOutputStream bos=null;
  129. try {
  130. Class.forName("oracle.jdbc.driver.OracleDriver");
  131. con = DriverManager.getConnection(
  132. "jdbc:oracle:thin:@10.23.117.149:1521:direct", "helpdesk", "helpdesk");
  133. //处理事务
  134. con.setAutoCommit(false);
  135. Statement st = con.createStatement();
  136. //              //插入一个空对象
  137. //              st.executeUpdate("insert into BLOBIMG  values(103,empty_blob())");
  138. String upsql="insert into hd_user(hduid,picture) values('"+Id+"',empty_blob())";
  139. st.executeQuery(upsql);
  140. //用for update方式锁定数据行
  141. String sql="select picture from hd_user where hduid='"+tempUser.getHduid()+"' for update";
  142. rs = st.executeQuery(sql);
  143. System.out.println(sql);
  144. //                  if (rs.next()) {
  145. //得到java.sql.Blob对象,然后Cast为oracle.sql.BLOB
  146. System.out.println(rs.getFetchSize());
  147. rs.next();
  148. oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);
  149. //到数据库的输出流
  150. os = blob.getBinaryOutputStream();
  151. bos=new BufferedOutputStream(os);
  152. //这里用一个文件模拟输入流
  153. File file = new File(serverLocalPath);
  154. in = new FileInputStream(file);
  155. bis=new BufferedInputStream(new FileInputStream(file));
  156. //将输入流写到输出流
  157. byte[] b = new byte[1024*1024];
  158. int len = 0;
  159. while (-1!=(len=bis.read(b, 0, b.length))) {
  160. bos.write(b, 0, len);
  161. }
  162. //              }
  163. catch (ClassNotFoundException e) {
  164. e.printStackTrace();
  165. catch (IOException e) {
  166. // TODO Auto-generated catch block
  167. e.printStackTrace();
  168. }catch (SQLException e) {
  169. // TODO Auto-generated catch block
  170. e.printStackTrace();
  171. }finally{
  172. if(os!=null){
  173. // os.flush();
  174. os.close();
  175. }
  176. if(bos!=null){
  177. // bos.flush();
  178. bos.close();
  179. }
  180. if(in!=null){
  181. in.close();
  182. }
  183. if(bis!=null){
  184. bis.close();
  185. }
  186. if(con!=null){
  187. con.commit();
  188. con.close();
  189. }
  190. }
  191. }
  192. /**
  193. * 增加用户,把照片从临时的上传目录下写入数据库Blob
  194. */
  195. public void addTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
  196. String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
  197. IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
  198. .getComponent(IKeyGen.BEAN_ID);
  199. String Id = keyService.getUUIDKey();
  200. tempUser.setHduid(Id);
  201. //默认字段
  202. tempUser.setCreate_date(new Date());
  203. tempUser.setCreator(loginUserJobNum);
  204. try {
  205. tempUser.setPicture(BLOB.empty_lob());
  206. catch (SQLException e2) {
  207. e2.printStackTrace();
  208. }
  209. Session s=this.getSessionFactory().openSession();
  210. Transaction t = s.beginTransaction();
  211. s.save(tempUser);
  212. s.flush();
  213. s.refresh(tempUser,LockMode.UPGRADE);  //锁定为更新模式
  214. try{
  215. File uploadFile=new File(serverLocalPath);
  216. FileInputStream fis = new FileInputStream(uploadFile);
  217. ByteArrayOutputStream out = new ByteArrayOutputStream();
  218. byte[] b = new byte[1024];
  219. int n;
  220. while ((n=fis.read(b)) != -1) {
  221. out.write(b,0,n);
  222. }
  223. fis.close();
  224. out.close();
  225. byte[] content = out.toByteArray();
  226. tempUser.setPicture(Hibernate.createBlob(content));
  227. s.flush();
  228. t.commit();
  229. s.close();
  230. }
  231. catch (FileNotFoundException e) {
  232. e.printStackTrace();
  233. catch (IOException e) {
  234. e.printStackTrace();
  235. }
  236. }
  237. /**
  238. * 编辑用户,把照片从临时的上传目录下写入数据库Blob
  239. */
  240. public void editTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
  241. String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
  242. //默认字段
  243. tempUser.setCreate_date(new Date());
  244. tempUser.setCreator(loginUserJobNum);
  245. try {
  246. tempUser.setPicture(BLOB.empty_lob());
  247. catch (SQLException e2) {
  248. e2.printStackTrace();
  249. }
  250. //      String nasql="update  hd_user g  set g.picture=null  " +
  251. //              " where g.hduid='"+tempUser.getHduid().trim()+"' ";
  252. //      this.createNativeSQL(nasql);
  253. Session s=this.getSessionFactory().openSession();
  254. Transaction t = s.beginTransaction();
  255. tempUser.setPicture(Hibernate.createBlob(new byte[1]));
  256. s.saveOrUpdate(tempUser);
  257. s.flush();
  258. s.refresh(tempUser,LockMode.UPGRADE);  //锁定为更新模式
  259. try{
  260. File uploadFile=new File(serverLocalPath);
  261. FileInputStream fis = new FileInputStream(uploadFile);
  262. ByteArrayOutputStream out = new ByteArrayOutputStream();
  263. byte[] b = new byte[1024];
  264. int n;
  265. while ((n=fis.read(b)) != -1) {
  266. out.write(b,0,n);
  267. }
  268. fis.close();
  269. out.close();
  270. byte[] content = out.toByteArray();
  271. tempUser.setPicture(Hibernate.createBlob(content));
  272. s.flush();
  273. t.commit();
  274. s.close();
  275. }
  276. catch (FileNotFoundException e) {
  277. e.printStackTrace();
  278. catch (IOException e) {
  279. e.printStackTrace();
  280. }
  281. }
  282. public void clearPhotoBlob(TempUser tempUser){
  283. String nasql="update  hd_user g  set g.picture=null  " +
  284. " where g.hduid='"+tempUser.getHduid().trim()+"' ";
  285. this.createNativeSQL(nasql);
  286. }
  287. /**
  288. * 编辑用户,不修改照片
  289. */
  290. public void editTempUserWithoutBlob(TempUser tempUser,String loginUserJobNum) {
  291. /*
  292. update hd_user t
  293. set t.uname='q',
  294. t.upass='q',
  295. t.realname='娜美',
  296. t.sex='女',
  297. t.email='tt@kdk.com',
  298. t.cellphone='45345345',
  299. t.ext='123',
  300. t.phone='321',
  301. t.job_level='坐席',
  302. t.edit_date=sysdate,
  303. t.editor='suolong',
  304. t.remark='editsuccess'
  305. where t.hduid='F15E73BD0A18084A01AFB22A54946F6F'
  306. */
  307. String hduid=tempUser.getHduid();
  308. if(hduid==null||hduid.trim().equals("")){
  309. }else{
  310. hduid=hduid.trim();
  311. String sql=" update hd_user t  " +
  312. "  set t.uname='"+tempUser.getUname().trim()+"', " +
  313. "  t.upass='"+tempUser.getUpass().trim()+"', " +
  314. "  t.realname='"+tempUser.getRealname()+"', " +
  315. "  t.sex='"+tempUser.getSex().trim()+"', " +
  316. "  t.email='"+tempUser.getEmail()+"', " +
  317. "  t.cellphone='"+tempUser.getCellphone()+"', " +
  318. "  t.ext='"+tempUser.getExt()+"', " +
  319. "  t.phone='"+tempUser.getPhone()+"', " +
  320. "  t.job_level='"+tempUser.getJob_level()+"', " +
  321. "  t.edit_date=sysdate, " +
  322. "  t.editor='"+loginUserJobNum+"', " +
  323. "  t.remark='"+tempUser.getRemark()+"'  " +
  324. "  where t.hduid='"+hduid+"' ";
  325. this.createNativeSQL(sql);
  326. }
  327. }
  328. }

BlobUtil.java

[java] view plaincopy
  1. package org.hd.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.sql.Blob;
  9. import java.sql.SQLException;
  10. import org.hibernate.Hibernate;
  11. public class BlobUtil {
  12. public static String WEBCONTENT_PATH="";
  13. public static String BASE_PATH="";
  14. public static String ODSUSER_PHOTO_PATH="";//ods用户头像目录
  15. public static String TEMPUSER_PHOTO_PATH="";//临时长期用户头像目录
  16. public static String TEMP_UPLOAD_PATH="";//上传时的临时目录
  17. public static String DirTypeTempupload="tempupload";
  18. public static String DirTypeOdsuser="odsuser";
  19. public static String DirTypeTempuser="tempuser";
  20. static{
  21. String clapath=BlobUtil.class.getResource("/").getPath();
  22. File claFile=new File(clapath);
  23. String basePath=claFile.getParentFile().getParentFile().getPath();
  24. WEBCONTENT_PATH=basePath;
  25. BASE_PATH=basePath+"\\tempphoto";
  26. File baseFile=new File(BASE_PATH);
  27. if(!baseFile.exists()){
  28. baseFile.mkdir();
  29. }
  30. ODSUSER_PHOTO_PATH=BASE_PATH+"\\odsuser";
  31. TEMPUSER_PHOTO_PATH=BASE_PATH+"\\tempuser";
  32. TEMP_UPLOAD_PATH=BASE_PATH+"\\tempupload";
  33. File odsFile=new File(ODSUSER_PHOTO_PATH);
  34. File tempFile=new File(TEMPUSER_PHOTO_PATH);
  35. File tempUpload=new File(TEMP_UPLOAD_PATH);
  36. if(!odsFile.exists()){
  37. odsFile.mkdir();
  38. }
  39. if(!tempFile.exists()){
  40. tempFile.mkdir();
  41. }
  42. if(!tempUpload.exists()){
  43. tempUpload.mkdir();
  44. }
  45. System.out.println(odsFile.getPath()+"---"+odsFile.exists());
  46. System.out.println(tempFile.getPath()+"---"+tempFile.exists());
  47. System.out.println(tempUpload.getPath()+"---"+tempUpload.exists());
  48. }
  49. public static String makeLocalPhoto(Blob blob,String tergetDirName,boolean isTempUser){
  50. String relativepath="";
  51. tergetDirName=tergetDirName.trim();
  52. if(blob==null){
  53. System.out.println("无法读取图片信息!");
  54. }else{
  55. if(tergetDirName==null||tergetDirName.trim().equals("")){
  56. System.out.println("无法获取工号创建目录!");
  57. }else{
  58. if(isTempUser){//临时长期用户
  59. File tempFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+tergetDirName);
  60. if(!tempFile.exists()){
  61. tempFile.mkdir();
  62. }
  63. boolean falg=blobToPhoto(blob,tempFile,tergetDirName);
  64. if(falg){
  65. relativepath="/tempphoto/tempuser/"+tergetDirName+"/"+tergetDirName+".jpg";
  66. }else{
  67. }
  68. }else{//ods用户
  69. File odsFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+tergetDirName);
  70. if(!odsFile.exists()){
  71. odsFile.mkdir();
  72. }
  73. boolean falg=blobToPhoto(blob,odsFile,tergetDirName);
  74. if(falg){
  75. relativepath="/tempphoto/odsuser/"+tergetDirName+"/"+tergetDirName+".jpg";
  76. }else{
  77. }
  78. }
  79. }
  80. }//end else
  81. return relativepath;
  82. }
  83. public static boolean blobToPhoto(Blob blob,File tergetDirFile,String tergetDirName){
  84. String photoPath=tergetDirFile.getPath().trim();
  85. boolean issuccess=true;
  86. if(!tergetDirFile.exists()){
  87. System.out.println("目标路径不存在"+tergetDirFile.getPath());
  88. issuccess=false;
  89. }else if(!tergetDirFile.isDirectory()){
  90. System.out.println("目标路径不是目录"+tergetDirFile.getPath());
  91. issuccess=false;
  92. }else{
  93. File photo=new File(photoPath+"\\"+tergetDirName.trim()+".jpg");
  94. FileOutputStream fos = null;
  95. InputStream is = null;
  96. byte[] Buffer = new byte[4096];
  97. try {
  98. is=blob.getBinaryStream();
  99. fos=new FileOutputStream(photo);
  100. int size = 0;
  101. while ((size = is.read(Buffer)) != -1) {
  102. fos.write(Buffer, 0, size);
  103. }
  104. catch (SQLException e) {
  105. e.printStackTrace();
  106. }  catch (FileNotFoundException e) {
  107. e.printStackTrace();
  108. catch (IOException e) {
  109. // TODO Auto-generated catch block
  110. e.printStackTrace();
  111. }catch (Exception e) {
  112. // TODO Auto-generated catch block
  113. e.printStackTrace();
  114. finally {
  115. try {
  116. if (fos != null) {
  117. fos.flush();
  118. fos.close();
  119. }
  120. if (is != null) {
  121. is.close();
  122. }
  123. catch (IOException e) {
  124. e.printStackTrace();
  125. }
  126. }
  127. }//end else
  128. return issuccess;
  129. }
  130. public static Blob photoToBlob(String filePath){
  131. Blob blob=null;
  132. FileInputStream fis = null;
  133. String serverLocalPath=BlobUtil.WEBCONTENT_PATH+filePath.replaceAll("/", "\\\\");
  134. System.out.println("serverLocalPath::"+serverLocalPath);
  135. File file=new File(serverLocalPath);
  136. try {
  137. fis=new FileInputStream(file);
  138. blob=Hibernate.createBlob(fis);
  139. }catch (FileNotFoundException e) {
  140. e.printStackTrace();
  141. catch (IOException e) {
  142. e.printStackTrace();
  143. }catch (Exception e) {
  144. e.printStackTrace();
  145. finally {
  146. try {
  147. if (fis != null) {
  148. fis.close();
  149. }
  150. catch (IOException e) {
  151. e.printStackTrace();
  152. }
  153. }
  154. return blob;
  155. }
  156. public static String getUploadTempPhotoUrl(String photoUrl,String jobNumber){
  157. String webUrl="";
  158. String toUrl="";
  159. File tempUploadFile=new File(BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber);
  160. if(!tempUploadFile.exists()){
  161. tempUploadFile.mkdir();
  162. }
  163. boolean falg=BlobUtil.isRightFileSuffix(photoUrl);
  164. if(falg){
  165. toUrl=BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber+"\\"+jobNumber+BlobUtil.getFileSuffix(photoUrl);
  166. BlobUtil.copyFile(photoUrl, toUrl);
  167. webUrl="/tempphoto/tempupload/"+jobNumber+"/"+jobNumber+BlobUtil.getFileSuffix(photoUrl);
  168. }else{
  169. }
  170. return webUrl;
  171. }
  172. //得到文件url文件的后缀
  173. public static String getFileSuffix(String fileUrl){
  174. String res="";
  175. int a=fileUrl.lastIndexOf(".");
  176. if(a>0){
  177. res=fileUrl.substring(a);
  178. }
  179. return res;
  180. }
  181. public static boolean isRightFileSuffix(String fileUrl){
  182. boolean flag=false;
  183. int a=fileUrl.lastIndexOf(".");
  184. if(a>0){
  185. flag=true;
  186. }
  187. return flag;
  188. }
  189. public static void copyFile(String fromUrl,String toUrl){
  190. File fromFile=new File(fromUrl);
  191. File toFile=new File(toUrl);
  192. if(toFile.exists()){
  193. toFile.delete();
  194. }
  195. FileOutputStream fos = null;
  196. FileInputStream fis = null;
  197. byte[] Buffer = new byte[4096];
  198. try {
  199. fis=new FileInputStream(fromFile);
  200. fos=new FileOutputStream(toFile);
  201. int size = 0;
  202. while ((size = fis.read(Buffer)) != -1) {
  203. fos.write(Buffer, 0, size);
  204. }
  205. }catch (FileNotFoundException e) {
  206. e.printStackTrace();
  207. catch (IOException e) {
  208. // TODO Auto-generated catch block
  209. e.printStackTrace();
  210. }catch (Exception e) {
  211. // TODO Auto-generated catch block
  212. e.printStackTrace();
  213. finally {
  214. try {
  215. if (fos != null) {
  216. fos.flush();
  217. fos.close();
  218. }
  219. if (fis != null) {
  220. fis.close();
  221. }
  222. catch (IOException e) {
  223. e.printStackTrace();
  224. }
  225. }
  226. }
  227. public static String makeDirByParamForOds(String jobNumberold,String type){
  228. String jobNumber=jobNumberold.trim();
  229. String rePath="";
  230. if(jobNumber==null||jobNumber.trim().equals("")){
  231. }else{
  232. if(type==BlobUtil.DirTypeTempupload){
  233. File tempUploadFile=new File(BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber);
  234. if(!tempUploadFile.exists()){
  235. tempUploadFile.mkdir();
  236. }
  237. rePath="/tempupload/"+jobNumber+"/"+jobNumber;
  238. }else if(type==BlobUtil.DirTypeOdsuser){
  239. File tempUploadFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+jobNumber);
  240. if(!tempUploadFile.exists()){
  241. tempUploadFile.mkdir();
  242. }
  243. rePath="/odsuser/"+jobNumber+"/"+jobNumber;
  244. }else if(type==BlobUtil.DirTypeTempuser){
  245. File tempUploadFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+jobNumber);
  246. if(!tempUploadFile.exists()){
  247. tempUploadFile.mkdir();
  248. }
  249. rePath="/tempuser/"+jobNumber+"/"+jobNumber;
  250. }
  251. }
  252. return rePath;
  253. }
  254. public static String makeDirByParamForOdsRealPath(String jobNumberold,String type){
  255. String jobNumber=jobNumberold.trim();
  256. String rePath="";
  257. if(jobNumber==null||jobNumber.trim().equals("")){
  258. }else{
  259. if(type==BlobUtil.DirTypeTempupload){
  260. File tempUploadFile=new File(BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber);
  261. if(!tempUploadFile.exists()){
  262. tempUploadFile.mkdir();
  263. }
  264. rePath="\\\\tempupload\\\\"+jobNumber+"\\\\"+jobNumber;
  265. }else if(type==BlobUtil.DirTypeOdsuser){
  266. File tempUploadFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+jobNumber);
  267. if(!tempUploadFile.exists()){
  268. tempUploadFile.mkdir();
  269. }
  270. rePath="\\\\odsuser\\\\"+jobNumber+"\\\\"+jobNumber;
  271. }else if(type==BlobUtil.DirTypeTempuser){
  272. File tempUploadFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+jobNumber);
  273. if(!tempUploadFile.exists()){
  274. tempUploadFile.mkdir();
  275. }
  276. rePath="\\\\tempuser\\\\"+jobNumber+"\\\\"+jobNumber;
  277. }
  278. }
  279. return rePath;
  280. }
  281. public static String changeFileName(String fullold,String filename,String newname){
  282. String res="";
  283. String a=filename.substring(0,filename.lastIndexOf("."));
  284. String b=BlobUtil.getFileSuffix(filename);
  285. res=fullold.replaceAll(filename, newname+b);
  286. return res;
  287. }
  288. public static void main(String[] ss){
  289. String serverLocalPath=BlobUtil.BASE_PATH+"/gg/gg.jpg".replaceAll("/", "\\\\");
  290. System.out.println("BASE_PATH::"+BlobUtil.BASE_PATH);
  291. System.out.println("WEBCONTENT_PATH::"+BlobUtil.WEBCONTENT_PATH);
  292. System.out.println("TEMP_UPLOAD_PATH::"+BlobUtil.TEMP_UPLOAD_PATH);
  293. System.out.println("ODSUSER_PHOTO_PATH::"+BlobUtil.ODSUSER_PHOTO_PATH);
  294. System.out.println("TEMPUSER_PHOTO_PATH::"+BlobUtil.TEMPUSER_PHOTO_PATH);
  295. String aa="sfs.333.jpgg";
  296. System.out.println(aa.substring(0,aa.lastIndexOf(".")));
  297. System.out.println(BlobUtil.changeFileName("as/asd/3.jpg","3.jpg","nn"));
  298. /*
  299. BASE_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto
  300. WEBCONTENT_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent
  301. TEMP_UPLOAD_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto\tempupload
  302. ODSUSER_PHOTO_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto\odsuser
  303. TEMPUSER_PHOTO_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto\tempuser
  304. */
  305. }
  306. }

TempUser.java

[java] view plaincopy
  1. package org.hd.tempuser.model;
  2. import java.util.Date;
  3. import java.sql.Blob;
  4. public class TempUser {
  5. //import oracle.sql.BLOB;
  6. private String hduid;
  7. private String uname;
  8. private String upass;
  9. private String realname;
  10. private String sex;
  11. private String email;
  12. private String utype;
  13. private String cellphone;
  14. private String ext;
  15. private String phone;
  16. private String job_level;
  17. private String valid;
  18. private Blob picture;
  19. private Date create_date;
  20. private String creator;
  21. private Date edit_date;
  22. private String editor;
  23. private String remark;
  24. //虚拟字段
  25. private String tempUrl;//照片url
  26. private String vjob_level;//职级
  27. public String getHduid() {
  28. return hduid;
  29. }
  30. public void setHduid(String hduid) {
  31. this.hduid = hduid;
  32. }
  33. public String getUname() {
  34. return uname;
  35. }
  36. public void setUname(String uname) {
  37. this.uname = uname;
  38. }
  39. public String getUpass() {
  40. return upass;
  41. }
  42. public void setUpass(String upass) {
  43. this.upass = upass;
  44. }
  45. public String getRealname() {
  46. return realname;
  47. }
  48. public void setRealname(String realname) {
  49. this.realname = realname;
  50. }
  51. public String getSex() {
  52. return sex;
  53. }
  54. public void setSex(String sex) {
  55. this.sex = sex;
  56. }
  57. public String getEmail() {
  58. return email;
  59. }
  60. public void setEmail(String email) {
  61. this.email = email;
  62. }
  63. public String getUtype() {
  64. return utype;
  65. }
  66. public void setUtype(String utype) {
  67. this.utype = utype;
  68. }
  69. public String getCellphone() {
  70. return cellphone;
  71. }
  72. public void setCellphone(String cellphone) {
  73. this.cellphone = cellphone;
  74. }
  75. public String getExt() {
  76. return ext;
  77. }
  78. public void setExt(String ext) {
  79. this.ext = ext;
  80. }
  81. public String getPhone() {
  82. return phone;
  83. }
  84. public void setPhone(String phone) {
  85. this.phone = phone;
  86. }
  87. public String getJob_level() {
  88. return job_level;
  89. }
  90. public void setJob_level(String job_level) {
  91. this.job_level = job_level;
  92. }
  93. public String getValid() {
  94. return valid;
  95. }
  96. public void setValid(String valid) {
  97. this.valid = valid;
  98. }
  99. public Blob getPicture() {
  100. return picture;
  101. }
  102. public void setPicture(Blob picture) {
  103. this.picture = picture;
  104. }
  105. public Date getCreate_date() {
  106. return create_date;
  107. }
  108. public void setCreate_date(Date create_date) {
  109. this.create_date = create_date;
  110. }
  111. public String getCreator() {
  112. return creator;
  113. }
  114. public void setCreator(String creator) {
  115. this.creator = creator;
  116. }
  117. public Date getEdit_date() {
  118. return edit_date;
  119. }
  120. public void setEdit_date(Date edit_date) {
  121. this.edit_date = edit_date;
  122. }
  123. public String getEditor() {
  124. return editor;
  125. }
  126. public void setEditor(String editor) {
  127. this.editor = editor;
  128. }
  129. public String getRemark() {
  130. return remark;
  131. }
  132. public void setRemark(String remark) {
  133. this.remark = remark;
  134. }
  135. public String getTempUrl() {
  136. return tempUrl;
  137. }
  138. public void setTempUrl(String tempUrl) {
  139. this.tempUrl = tempUrl;
  140. }
  141. public String getVjob_level() {
  142. return vjob_level;
  143. }
  144. public void setVjob_level(String vjob_level) {
  145. this.vjob_level = vjob_level;
  146. }
  147. }

TempUser.hbm.xml

[java] view plaincopy
  1. <?xml version="1.0"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <class name="org.hd.tempuser.model.TempUser" table="hd_user">
  7. <id name="hduid" type="java.lang.String">
  8. <column name="hduid" length="32" />
  9. <generator class="assigned" />
  10. </id>
  11. <property name="uname" type="java.lang.String">
  12. <column name="uname" length="50">
  13. </column>
  14. </property>
  15. <property name="upass" type="java.lang.String">
  16. <column name="upass" length="100" />
  17. </property>
  18. <property name="realname" type="java.lang.String">
  19. <column name="realname" length="50">
  20. </column>
  21. </property>
  22. <property name="sex" type="java.lang.String">
  23. <column name="sex" length="50" />
  24. </property>
  25. <property name="email" type="java.lang.String">
  26. <column name="email" length="100">
  27. </column>
  28. </property>
  29. <property name="utype" type="java.lang.String">
  30. <column name="utype" length="10" />
  31. </property>
  32. <property name="cellphone" type="java.lang.String">
  33. <column name="cellphone" length="50">
  34. </column>
  35. </property>
  36. <property name="ext" type="java.lang.String">
  37. <column name="ext" length="50" />
  38. </property>
  39. <property name="phone" type="java.lang.String">
  40. <column name="phone" length="50" />
  41. </property>
  42. <property name="job_level" type="java.lang.String">
  43. <column name="job_level" length="50" />
  44. </property>
  45. <property name="valid" type="java.lang.String">
  46. <column name="valid" length="10" />
  47. </property>
  48. <property name="picture" type="java.sql.Blob">
  49. <column name="picture" />
  50. </property>
  51. <property name="create_date" type="java.util.Date">
  52. <column name="create_date" />
  53. </property>
  54. <property name="creator" type="java.lang.String">
  55. <column name="creator" length="32" />
  56. </property>
  57. <property name="edit_date" type="java.util.Date">
  58. <column name="edit_date" />
  59. </property>
  60. <property name="editor" type="java.lang.String">
  61. <column name="editor" length="32" />
  62. </property>
  63. <property name="remark" type="java.lang.String">
  64. <column name="remark" length="200" />
  65. </property>
  66. </class>
  67. </hibernate-mapping>

picture是Blob字段(照片)

从上面的代码中说说核心代码;

写入Blob。

在新增时,picture首先需要赋值一个空的值,这个空值不是null  !!!而是BLOB.empty_lob()或者Hibernate.createBlob(new byte[1])

这样才算是符合Blob类型。

session需要改变更新模式 s.refresh(tempUser,LockMode.UPGRADE);  //锁定为更新模式

即for update.

这是才可以写入,二写入的内容是byte[]类型!

[java] view plaincopy
  1. /**
  2. * 增加用户,把照片从临时的上传目录下写入数据库Blob
  3. */
  4. public void addTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
  5. String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
  6. IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
  7. .getComponent(IKeyGen.BEAN_ID);
  8. String Id = keyService.getUUIDKey();
  9. tempUser.setHduid(Id);
  10. //默认字段
  11. tempUser.setCreate_date(new Date());
  12. tempUser.setCreator(loginUserJobNum);
  13. try {
  14. tempUser.setPicture(BLOB.empty_lob());
  15. catch (SQLException e2) {
  16. e2.printStackTrace();
  17. }
  18. Session s=this.getSessionFactory().openSession();
  19. Transaction t = s.beginTransaction();
  20. s.save(tempUser);
  21. s.flush();
  22. s.refresh(tempUser,LockMode.UPGRADE);  //锁定为更新模式
  23. try{
  24. File uploadFile=new File(serverLocalPath);
  25. FileInputStream fis = new FileInputStream(uploadFile);
  26. ByteArrayOutputStream out = new ByteArrayOutputStream();
  27. byte[] b = new byte[1024];
  28. int n;
  29. while ((n=fis.read(b)) != -1) {
  30. out.write(b,0,n);
  31. }
  32. fis.close();
  33. out.close();
  34. byte[] content = out.toByteArray();
  35. tempUser.setPicture(Hibernate.createBlob(content));
  36. s.flush();
  37. t.commit();
  38. s.close();
  39. }
  40. catch (FileNotFoundException e) {
  41. e.printStackTrace();
  42. catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45. }

编辑用户时,需要先把数据库的Blob字段置空null,然后再更新(不知有没有其他直接更新的方法)

所以在action我先tempUserService.clearPhotoBlob(getEditTempUser());

[java] view plaincopy
  1. public void clearPhotoBlob(TempUser tempUser){
  2. String nasql="update  hd_user g  set g.picture=null  " +
  3. " where g.hduid='"+tempUser.getHduid().trim()+"' ";
  4. this.createNativeSQL(nasql);
  5. }

然后再更新blob,

tempUserService.editTempUserWriteBlob(getEditTempUser(),
          getLocalPhotoUrl(), loginUserJobNum);

[java] view plaincopy
  1. /**
  2. * 编辑用户,把照片从临时的上传目录下写入数据库Blob
  3. */
  4. public void editTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
  5. String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
  6. //默认字段
  7. tempUser.setCreate_date(new Date());
  8. tempUser.setCreator(loginUserJobNum);
  9. try {
  10. tempUser.setPicture(BLOB.empty_lob());
  11. catch (SQLException e2) {
  12. e2.printStackTrace();
  13. }
  14. //      String nasql="update  hd_user g  set g.picture=null  " +
  15. //              " where g.hduid='"+tempUser.getHduid().trim()+"' ";
  16. //      this.createNativeSQL(nasql);
  17. Session s=this.getSessionFactory().openSession();
  18. Transaction t = s.beginTransaction();
  19. tempUser.setPicture(Hibernate.createBlob(new byte[1]));
  20. s.saveOrUpdate(tempUser);
  21. s.flush();
  22. s.refresh(tempUser,LockMode.UPGRADE);  //锁定为更新模式
  23. try{
  24. File uploadFile=new File(serverLocalPath);
  25. FileInputStream fis = new FileInputStream(uploadFile);
  26. ByteArrayOutputStream out = new ByteArrayOutputStream();
  27. byte[] b = new byte[1024];
  28. int n;
  29. while ((n=fis.read(b)) != -1) {
  30. out.write(b,0,n);
  31. }
  32. fis.close();
  33. out.close();
  34. byte[] content = out.toByteArray();
  35. tempUser.setPicture(Hibernate.createBlob(content));
  36. s.flush();
  37. t.commit();
  38. s.close();
  39. }
  40. catch (FileNotFoundException e) {
  41. e.printStackTrace();
  42. catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45. }

至于读取Blob,你只需要先读取出来放到服务器下某个路径,然后返回这个路径用于页面展示。

例如,在查看用户信息的时候,需要展示照片。

[java] view plaincopy
  1. //读取TempUser照片信息
  2. public String getTempPhoto(TempUser tempUser){
  3. String resPath="";
  4. if(tempUser==null){
  5. }else if(tempUser.getPicture()==null){
  6. }else{
  7. Blob blob=(Blob)tempUser.getPicture();
  8. resPath=BlobUtil.makeLocalPhoto(blob, tempUser.getUname(), true);
  9. }//end else
  10. return resPath;
  11. }

其中

[java] view plaincopy
  1. public static String makeLocalPhoto(Blob blob,String tergetDirName,boolean isTempUser){
  2. String relativepath="";
  3. tergetDirName=tergetDirName.trim();
  4. if(blob==null){
  5. System.out.println("无法读取图片信息!");
  6. }else{
  7. if(tergetDirName==null||tergetDirName.trim().equals("")){
  8. System.out.println("无法获取工号创建目录!");
  9. }else{
  10. if(isTempUser){//临时长期用户
  11. File tempFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+tergetDirName);
  12. if(!tempFile.exists()){
  13. tempFile.mkdir();
  14. }
  15. boolean falg=blobToPhoto(blob,tempFile,tergetDirName);
  16. if(falg){
  17. relativepath="/tempphoto/tempuser/"+tergetDirName+"/"+tergetDirName+".jpg";
  18. }else{
  19. }
  20. }else{//ods用户
  21. File odsFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+tergetDirName);
  22. if(!odsFile.exists()){
  23. odsFile.mkdir();
  24. }
  25. boolean falg=blobToPhoto(blob,odsFile,tergetDirName);
  26. if(falg){
  27. relativepath="/tempphoto/odsuser/"+tergetDirName+"/"+tergetDirName+".jpg";
  28. }else{
  29. }
  30. }
  31. }
  32. }//end else
  33. return relativepath;
  34. }

其中

[java] view plaincopy
  1. public static boolean blobToPhoto(Blob blob,File tergetDirFile,String tergetDirName){
  2. String photoPath=tergetDirFile.getPath().trim();
  3. boolean issuccess=true;
  4. if(!tergetDirFile.exists()){
  5. System.out.println("目标路径不存在"+tergetDirFile.getPath());
  6. issuccess=false;
  7. }else if(!tergetDirFile.isDirectory()){
  8. System.out.println("目标路径不是目录"+tergetDirFile.getPath());
  9. issuccess=false;
  10. }else{
  11. File photo=new File(photoPath+"\\"+tergetDirName.trim()+".jpg");
  12. FileOutputStream fos = null;
  13. InputStream is = null;
  14. byte[] Buffer = new byte[4096];
  15. try {
  16. is=blob.getBinaryStream();
  17. fos=new FileOutputStream(photo);
  18. int size = 0;
  19. while ((size = is.read(Buffer)) != -1) {
  20. fos.write(Buffer, 0, size);
  21. }
  22. catch (SQLException e) {
  23. e.printStackTrace();
  24. }  catch (FileNotFoundException e) {
  25. e.printStackTrace();
  26. catch (IOException e) {
  27. // TODO Auto-generated catch block
  28. e.printStackTrace();
  29. }catch (Exception e) {
  30. // TODO Auto-generated catch block
  31. e.printStackTrace();
  32. finally {
  33. try {
  34. if (fos != null) {
  35. fos.flush();
  36. fos.close();
  37. }
  38. if (is != null) {
  39. is.close();
  40. }
  41. catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }//end else
  46. return issuccess;
  47. }

这里读出来的图片都是.jpg格式的,因为后缀我写死了,这里还不完善。

注意:你需要传入已经上传到服务器的文件的地址,这个用个工具类实现BlobUtil.java。

这样管理比较清晰。

上传图片至服务器,写入到数据库Blob字段中,以及从数据库读取Blob信息(iframe父子页面传值)(2)相关推荐

  1. 上传图片至服务器,写入到数据库Blob字段中,以及从数据库读取Blob信息(iframe父子页面传值)(1)

    最近做了个用户维护功能,涉及到照片的操作. 照片是存到数据库oracle中的Blob字段中. 难点有两个: 1,图片的上传:2,Blob字段的读取. 先说图片的上传吧, 我使用common-fileu ...

  2. delphi mysql dll直接_十万火急!!!那位高手用过libmysql.dll直接连接MySql数据库?如何将二进制文件保存到blob字段中? (60分)...

    先用php+mysql将文件通过web方式保存到远程的服务器的blob字段中,然后用 delphi+libmysql.dll直接连接远程MySql数据库,再将数据复制到本地的MySql数据库中. 代码 ...

  3. 图片上传到数据库,保存到Blob字段中

    需求:从系统上传图片,将图片信息保存到数据库的blob字段中,并提供照片的查询接口 controller: package com.success.controller;import ../*** 系 ...

  4. 将页面多个下拉框的值以字符串拼接方式存放至数据库一个字段中

     1,当页面中有多个值,传入Controller并以字符串拼接方式,以","隔开存放至数据库一个字段中,页面中多个<select name="off"&g ...

  5. Java中对查出的数据计数_基础算法7:从数据库某个字段中取出现次数最多的几条数据形成“热门xxx”...

    在这里,我们需要查出所有的"出发城市"和"到达城市",并对每个城市进行计数根据其出现次数来取出几个出现次数最多的城市为热门城市 注:将多个字段的数据合并在一起并 ...

  6. 如何使用SQL批量替换数据库特定字段中部分特定数据

    1.替换数据库特定字段中部分特定数据的SQL语句 SQL语句:update 表名 set 字段名= replace(字段名,'原字符串',需要替换成的字符串') 以将表exam_major中的字段po ...

  7. cmd查看mysql数据库表_cmd中查看MySQL数据库表数据及结构

    0. 1 .cmd进入mysql安装的bin目录(C:\Program Files\XXXXXX\MySQL Server 5.6\bin) mysql -hlocalhost -uroot -p 回 ...

  8. 用python将中文/汉字写入文本文档或者从文本文档读取中文信息

    用python将中文/汉字写入文本文档或者从文本文档读取中文信息 经常有同学碰到通过python无法将汉字信息写入文本,或者无法读取文本里的汉字信息的情况,下面用一种最简单的方式解决这个问题. 写入文 ...

  9. oracle blob字段索引,在oracle 数据库中使用 Blob 字段存储 一张图片并读取

    1. 进行数据库的设置  create table image_lob(t_id varchar2(5) not null,t_image blob not null); create or repl ...

最新文章

  1. Oracle 基础练习
  2. 将枚举值转换为DropDownList等的选项值
  3. 怎么在vue的@click里面直接写js_【转】为 Node.js 贡献你的力量 ———— 调试代码
  4. 解决因删除外键引用的时候导致相应字段被删除了的问题
  5. YbtOJ#652-集合比较【Treap】
  6. win8信息服务器不可用怎么办,win8系统下开机提示OneDrive选项此服务现在不可用请稍后再试怎么办...
  7. 周围剃光头顶留长发型_?22岁亿万富翁凯莉登杂志,顶着5斤“鸟窝头”凹造型,绝代艳后...
  8. Latex 图像总是出现在目标页的下一页置顶
  9. 《逆袭进大厂》之C++篇49问49答(绝对的干货)
  10. StructureMap 作为 ASP.NET MVC 的 DI 框架的使用实例
  11. Android-7.0-Nuplayer-启动流程
  12. 判刑不应区分未成年、精神病
  13. 冰点还原离线激活_冰点还原密钥,小编教你如何激活冰点还原
  14. 华为云PBX_基于华为云客服平台打造的比特百灵鸟AI管家解决方案发布
  15. java 加密 —— 对称加密、非对称加密、消息摘要
  16. HTML与Java组合使用_【自学java笔记#第五十四天#】javaweb day02 html和css的组合使用...
  17. Leecode第九天,广度优先搜索之矩阵,腐烂的橘子
  18. python读取文件r_python读入文件时加r的作用?
  19. Atom编译器64位win版本下载汉化及前端必备插件
  20. UE4蓝图案例:媒体播放器的开关1

热门文章

  1. list python 访问 键值对_学完Python,我决定熬夜整理这篇总结...
  2. 在URP中使用UICamera
  3. unity Mirror使用笔记
  4. android java写文件_Android中文件的读写(一)----流操作
  5. 使用绑定进行WPF DataGrid格式化的指南
  6. 什么是数据库触发器?
  7. java正则获取数字_Java通过正则表达式获取字符串中数字的方法示例
  8. python string.format()_python string format
  9. 石头剪刀布python代码_Python实现的石头剪子布代码分享
  10. Django 报错 ‘polls‘ is not a registered namespace