上传图片至服务器,写入到数据库Blob字段中,以及从数据库读取Blob信息(iframe父子页面传值)(2)
首先说写入oracle的Blob字段
上一文章的实现方法没有贴出来,如下:
TempUserService.java
- package org.hd.tempuser.service;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.sql.Blob;
- import java.sql.SQLException;
- import java.util.List;
- import java.util.Map;
- import org.hd.tempuser.model.TempUser;
- import org.rd.framework.query.support.PaginationSupport;
- public interface TempUserService {
- public static final String BEAN_ID = "tempUserService";
- public List getTempUserList(Map queryParams,PaginationSupport paginationSupport);
- public TempUser getTempUserById(String tempuserid);
- public void delTempUserById(String tempuserid);
- public TempUser addTempUser(TempUser tempUser);
- public void editTempUser(TempUser tempUser);
- public void addTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum);
- public void editTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum);
- public void editTempUserWithoutBlob(TempUser tempUser,String loginUserJobNum);
- public void clearPhotoBlob(TempUser tempUser);
- }
TempUserServiceImpl.java
- package org.hd.tempuser.service.impl;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.sql.Blob;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.Date;
- import java.util.List;
- import java.util.Map;
- import oracle.sql.BLOB;
- import org.hd.tempuser.model.TempUser;
- import org.hd.tempuser.service.TempUserService;
- import org.hd.util.BlobUtil;
- import org.hibernate.Hibernate;
- import org.hibernate.LockMode;
- import org.hibernate.Session;
- import org.hibernate.Transaction;
- import org.hibernate.lob.SerializableBlob;
- import org.rd.framework.common.container.ContainerManager;
- import org.rd.framework.dao.impl.CommonServiceImpl;
- import org.rd.framework.keygen.IKeyGen;
- import org.rd.framework.query.support.PaginationSupport;
- import org.rd.framework.util.WebUtils;
- public class TempUserServiceImpl extends CommonServiceImpl implements TempUserService{
- @Override
- public List getTempUserList(Map queryParams,
- PaginationSupport paginationSupport) {
- String qualificationString = WebUtils.getQualificationString(queryParams);
- String queryString = "select queryby from TempUser queryby" + qualificationString;
- String countString = "select count(queryby.hduid) from TempUser queryby" + qualificationString;
- paginationSupport.setTotalCount(count(countString));
- return find(queryString, paginationSupport);
- }
- public TempUser getTempUserById(String tempuserid){
- TempUser tempUser=null;
- String queryString = "select queryby from TempUser queryby where queryby.hduid='"
- + tempuserid.trim()+"'";
- List list=find(queryString);
- if(list.size()>0){
- tempUser=(TempUser)list.get(0);
- }
- return tempUser;
- }
- public void delTempUserById(String tempuserid){
- TempUser tempUser=null;
- String queryString = "delete from hd_user queryby where queryby.hduid='"
- + tempuserid.trim()+"'";
- if(tempuserid==null||tempuserid.equals("")){
- }else{
- createNativeSQL(queryString);
- }
- }
- public TempUser addTempUser(TempUser tempUser){
- IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
- .getComponent(IKeyGen.BEAN_ID);
- String Id = keyService.getUUIDKey();
- tempUser.setHduid(Id);
- //默认字段
- // tempUser.setCreate_date(new Date());
- // tempUser.setCreator(creator)
- create(tempUser);
- return tempUser;
- }
- public void editTempUser(TempUser tempUser){
- this.update(tempUser);
- }
- //此方法作废
- public void addTempUserTt(TempUser tempUser,Blob hbblob,String pathh){
- String serverLocalPath=BlobUtil.WEBCONTENT_PATH+pathh.replaceAll("/", "\\\\");
- IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
- .getComponent(IKeyGen.BEAN_ID);
- String Id = keyService.getUUIDKey();
- tempUser.setHduid(Id);
- Session s = null;
- byte[] buffer = new byte[1];
- buffer[0] = 1;
- try {
- s = this.getSessionFactory().openSession();
- Transaction tx = s.beginTransaction();
- s.save(tempUser);
- s.flush();
- s.refresh(tempUser, LockMode.UPGRADE);
- BLOB blob = (BLOB)hbblob;
- OutputStream out = blob.getBinaryOutputStream();
- // String fileName = "oraclejdbc.jar";
- File f = new File(serverLocalPath);
- FileInputStream fin = new FileInputStream(f);
- int count = -1, total = 0;
- byte[] data = new byte[(int)fin.available()];
- fin.read(data);
- out.write(data);
- fin.close();
- out.close();
- s.flush();
- tx.commit();
- } catch (Exception e){
- System.out.println(e.getMessage());
- } finally {
- if (s != null);
- try {
- s.close();;
- } catch (Exception e) {}
- }
- }
- //此方法作废
- public void addTempUserTtdd(TempUser tempUser,Blob hbblob,String pathh) throws SQLException, IOException, FileNotFoundException{
- String serverLocalPath=BlobUtil.WEBCONTENT_PATH+pathh.replaceAll("/", "\\\\");
- IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
- .getComponent(IKeyGen.BEAN_ID);
- String Id = keyService.getUUIDKey();
- tempUser.setHduid(Id);
- //得到数据库连接(驱动包是weblogic的,没有下载任何新版本)
- Connection con=null;
- ResultSet rs=null;
- InputStream in=null;
- BufferedInputStream bis=null;
- OutputStream os=null;
- BufferedOutputStream bos=null;
- try {
- Class.forName("oracle.jdbc.driver.OracleDriver");
- con = DriverManager.getConnection(
- "jdbc:oracle:thin:@10.23.117.149:1521:direct", "helpdesk", "helpdesk");
- //处理事务
- con.setAutoCommit(false);
- Statement st = con.createStatement();
- // //插入一个空对象
- // st.executeUpdate("insert into BLOBIMG values(103,empty_blob())");
- String upsql="insert into hd_user(hduid,picture) values('"+Id+"',empty_blob())";
- st.executeQuery(upsql);
- //用for update方式锁定数据行
- String sql="select picture from hd_user where hduid='"+tempUser.getHduid()+"' for update";
- rs = st.executeQuery(sql);
- System.out.println(sql);
- // if (rs.next()) {
- //得到java.sql.Blob对象,然后Cast为oracle.sql.BLOB
- System.out.println(rs.getFetchSize());
- rs.next();
- oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);
- //到数据库的输出流
- os = blob.getBinaryOutputStream();
- bos=new BufferedOutputStream(os);
- //这里用一个文件模拟输入流
- File file = new File(serverLocalPath);
- in = new FileInputStream(file);
- bis=new BufferedInputStream(new FileInputStream(file));
- //将输入流写到输出流
- byte[] b = new byte[1024*1024];
- int len = 0;
- while (-1!=(len=bis.read(b, 0, b.length))) {
- bos.write(b, 0, len);
- }
- // }
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- if(os!=null){
- // os.flush();
- os.close();
- }
- if(bos!=null){
- // bos.flush();
- bos.close();
- }
- if(in!=null){
- in.close();
- }
- if(bis!=null){
- bis.close();
- }
- if(con!=null){
- con.commit();
- con.close();
- }
- }
- }
- /**
- * 增加用户,把照片从临时的上传目录下写入数据库Blob
- */
- public void addTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
- String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
- IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
- .getComponent(IKeyGen.BEAN_ID);
- String Id = keyService.getUUIDKey();
- tempUser.setHduid(Id);
- //默认字段
- tempUser.setCreate_date(new Date());
- tempUser.setCreator(loginUserJobNum);
- try {
- tempUser.setPicture(BLOB.empty_lob());
- } catch (SQLException e2) {
- e2.printStackTrace();
- }
- Session s=this.getSessionFactory().openSession();
- Transaction t = s.beginTransaction();
- s.save(tempUser);
- s.flush();
- s.refresh(tempUser,LockMode.UPGRADE); //锁定为更新模式
- try{
- File uploadFile=new File(serverLocalPath);
- FileInputStream fis = new FileInputStream(uploadFile);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] b = new byte[1024];
- int n;
- while ((n=fis.read(b)) != -1) {
- out.write(b,0,n);
- }
- fis.close();
- out.close();
- byte[] content = out.toByteArray();
- tempUser.setPicture(Hibernate.createBlob(content));
- s.flush();
- t.commit();
- s.close();
- }
- catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 编辑用户,把照片从临时的上传目录下写入数据库Blob
- */
- public void editTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
- String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
- //默认字段
- tempUser.setCreate_date(new Date());
- tempUser.setCreator(loginUserJobNum);
- try {
- tempUser.setPicture(BLOB.empty_lob());
- } catch (SQLException e2) {
- e2.printStackTrace();
- }
- // String nasql="update hd_user g set g.picture=null " +
- // " where g.hduid='"+tempUser.getHduid().trim()+"' ";
- // this.createNativeSQL(nasql);
- Session s=this.getSessionFactory().openSession();
- Transaction t = s.beginTransaction();
- tempUser.setPicture(Hibernate.createBlob(new byte[1]));
- s.saveOrUpdate(tempUser);
- s.flush();
- s.refresh(tempUser,LockMode.UPGRADE); //锁定为更新模式
- try{
- File uploadFile=new File(serverLocalPath);
- FileInputStream fis = new FileInputStream(uploadFile);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] b = new byte[1024];
- int n;
- while ((n=fis.read(b)) != -1) {
- out.write(b,0,n);
- }
- fis.close();
- out.close();
- byte[] content = out.toByteArray();
- tempUser.setPicture(Hibernate.createBlob(content));
- s.flush();
- t.commit();
- s.close();
- }
- catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void clearPhotoBlob(TempUser tempUser){
- String nasql="update hd_user g set g.picture=null " +
- " where g.hduid='"+tempUser.getHduid().trim()+"' ";
- this.createNativeSQL(nasql);
- }
- /**
- * 编辑用户,不修改照片
- */
- public void editTempUserWithoutBlob(TempUser tempUser,String loginUserJobNum) {
- /*
- update hd_user t
- set t.uname='q',
- t.upass='q',
- t.realname='娜美',
- t.sex='女',
- t.email='tt@kdk.com',
- t.cellphone='45345345',
- t.ext='123',
- t.phone='321',
- t.job_level='坐席',
- t.edit_date=sysdate,
- t.editor='suolong',
- t.remark='editsuccess'
- where t.hduid='F15E73BD0A18084A01AFB22A54946F6F'
- */
- String hduid=tempUser.getHduid();
- if(hduid==null||hduid.trim().equals("")){
- }else{
- hduid=hduid.trim();
- String sql=" update hd_user t " +
- " set t.uname='"+tempUser.getUname().trim()+"', " +
- " t.upass='"+tempUser.getUpass().trim()+"', " +
- " t.realname='"+tempUser.getRealname()+"', " +
- " t.sex='"+tempUser.getSex().trim()+"', " +
- " t.email='"+tempUser.getEmail()+"', " +
- " t.cellphone='"+tempUser.getCellphone()+"', " +
- " t.ext='"+tempUser.getExt()+"', " +
- " t.phone='"+tempUser.getPhone()+"', " +
- " t.job_level='"+tempUser.getJob_level()+"', " +
- " t.edit_date=sysdate, " +
- " t.editor='"+loginUserJobNum+"', " +
- " t.remark='"+tempUser.getRemark()+"' " +
- " where t.hduid='"+hduid+"' ";
- this.createNativeSQL(sql);
- }
- }
- }
BlobUtil.java
- package org.hd.util;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.sql.Blob;
- import java.sql.SQLException;
- import org.hibernate.Hibernate;
- public class BlobUtil {
- public static String WEBCONTENT_PATH="";
- public static String BASE_PATH="";
- public static String ODSUSER_PHOTO_PATH="";//ods用户头像目录
- public static String TEMPUSER_PHOTO_PATH="";//临时长期用户头像目录
- public static String TEMP_UPLOAD_PATH="";//上传时的临时目录
- public static String DirTypeTempupload="tempupload";
- public static String DirTypeOdsuser="odsuser";
- public static String DirTypeTempuser="tempuser";
- static{
- String clapath=BlobUtil.class.getResource("/").getPath();
- File claFile=new File(clapath);
- String basePath=claFile.getParentFile().getParentFile().getPath();
- WEBCONTENT_PATH=basePath;
- BASE_PATH=basePath+"\\tempphoto";
- File baseFile=new File(BASE_PATH);
- if(!baseFile.exists()){
- baseFile.mkdir();
- }
- ODSUSER_PHOTO_PATH=BASE_PATH+"\\odsuser";
- TEMPUSER_PHOTO_PATH=BASE_PATH+"\\tempuser";
- TEMP_UPLOAD_PATH=BASE_PATH+"\\tempupload";
- File odsFile=new File(ODSUSER_PHOTO_PATH);
- File tempFile=new File(TEMPUSER_PHOTO_PATH);
- File tempUpload=new File(TEMP_UPLOAD_PATH);
- if(!odsFile.exists()){
- odsFile.mkdir();
- }
- if(!tempFile.exists()){
- tempFile.mkdir();
- }
- if(!tempUpload.exists()){
- tempUpload.mkdir();
- }
- System.out.println(odsFile.getPath()+"---"+odsFile.exists());
- System.out.println(tempFile.getPath()+"---"+tempFile.exists());
- System.out.println(tempUpload.getPath()+"---"+tempUpload.exists());
- }
- public static String makeLocalPhoto(Blob blob,String tergetDirName,boolean isTempUser){
- String relativepath="";
- tergetDirName=tergetDirName.trim();
- if(blob==null){
- System.out.println("无法读取图片信息!");
- }else{
- if(tergetDirName==null||tergetDirName.trim().equals("")){
- System.out.println("无法获取工号创建目录!");
- }else{
- if(isTempUser){//临时长期用户
- File tempFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+tergetDirName);
- if(!tempFile.exists()){
- tempFile.mkdir();
- }
- boolean falg=blobToPhoto(blob,tempFile,tergetDirName);
- if(falg){
- relativepath="/tempphoto/tempuser/"+tergetDirName+"/"+tergetDirName+".jpg";
- }else{
- }
- }else{//ods用户
- File odsFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+tergetDirName);
- if(!odsFile.exists()){
- odsFile.mkdir();
- }
- boolean falg=blobToPhoto(blob,odsFile,tergetDirName);
- if(falg){
- relativepath="/tempphoto/odsuser/"+tergetDirName+"/"+tergetDirName+".jpg";
- }else{
- }
- }
- }
- }//end else
- return relativepath;
- }
- public static boolean blobToPhoto(Blob blob,File tergetDirFile,String tergetDirName){
- String photoPath=tergetDirFile.getPath().trim();
- boolean issuccess=true;
- if(!tergetDirFile.exists()){
- System.out.println("目标路径不存在"+tergetDirFile.getPath());
- issuccess=false;
- }else if(!tergetDirFile.isDirectory()){
- System.out.println("目标路径不是目录"+tergetDirFile.getPath());
- issuccess=false;
- }else{
- File photo=new File(photoPath+"\\"+tergetDirName.trim()+".jpg");
- FileOutputStream fos = null;
- InputStream is = null;
- byte[] Buffer = new byte[4096];
- try {
- is=blob.getBinaryStream();
- fos=new FileOutputStream(photo);
- int size = 0;
- while ((size = is.read(Buffer)) != -1) {
- fos.write(Buffer, 0, size);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- try {
- if (fos != null) {
- fos.flush();
- fos.close();
- }
- if (is != null) {
- is.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }//end else
- return issuccess;
- }
- public static Blob photoToBlob(String filePath){
- Blob blob=null;
- FileInputStream fis = null;
- String serverLocalPath=BlobUtil.WEBCONTENT_PATH+filePath.replaceAll("/", "\\\\");
- System.out.println("serverLocalPath::"+serverLocalPath);
- File file=new File(serverLocalPath);
- try {
- fis=new FileInputStream(file);
- blob=Hibernate.createBlob(fis);
- }catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (fis != null) {
- fis.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return blob;
- }
- public static String getUploadTempPhotoUrl(String photoUrl,String jobNumber){
- String webUrl="";
- String toUrl="";
- File tempUploadFile=new File(BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber);
- if(!tempUploadFile.exists()){
- tempUploadFile.mkdir();
- }
- boolean falg=BlobUtil.isRightFileSuffix(photoUrl);
- if(falg){
- toUrl=BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber+"\\"+jobNumber+BlobUtil.getFileSuffix(photoUrl);
- BlobUtil.copyFile(photoUrl, toUrl);
- webUrl="/tempphoto/tempupload/"+jobNumber+"/"+jobNumber+BlobUtil.getFileSuffix(photoUrl);
- }else{
- }
- return webUrl;
- }
- //得到文件url文件的后缀
- public static String getFileSuffix(String fileUrl){
- String res="";
- int a=fileUrl.lastIndexOf(".");
- if(a>0){
- res=fileUrl.substring(a);
- }
- return res;
- }
- public static boolean isRightFileSuffix(String fileUrl){
- boolean flag=false;
- int a=fileUrl.lastIndexOf(".");
- if(a>0){
- flag=true;
- }
- return flag;
- }
- public static void copyFile(String fromUrl,String toUrl){
- File fromFile=new File(fromUrl);
- File toFile=new File(toUrl);
- if(toFile.exists()){
- toFile.delete();
- }
- FileOutputStream fos = null;
- FileInputStream fis = null;
- byte[] Buffer = new byte[4096];
- try {
- fis=new FileInputStream(fromFile);
- fos=new FileOutputStream(toFile);
- int size = 0;
- while ((size = fis.read(Buffer)) != -1) {
- fos.write(Buffer, 0, size);
- }
- }catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- try {
- if (fos != null) {
- fos.flush();
- fos.close();
- }
- if (fis != null) {
- fis.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public static String makeDirByParamForOds(String jobNumberold,String type){
- String jobNumber=jobNumberold.trim();
- String rePath="";
- if(jobNumber==null||jobNumber.trim().equals("")){
- }else{
- if(type==BlobUtil.DirTypeTempupload){
- File tempUploadFile=new File(BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber);
- if(!tempUploadFile.exists()){
- tempUploadFile.mkdir();
- }
- rePath="/tempupload/"+jobNumber+"/"+jobNumber;
- }else if(type==BlobUtil.DirTypeOdsuser){
- File tempUploadFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+jobNumber);
- if(!tempUploadFile.exists()){
- tempUploadFile.mkdir();
- }
- rePath="/odsuser/"+jobNumber+"/"+jobNumber;
- }else if(type==BlobUtil.DirTypeTempuser){
- File tempUploadFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+jobNumber);
- if(!tempUploadFile.exists()){
- tempUploadFile.mkdir();
- }
- rePath="/tempuser/"+jobNumber+"/"+jobNumber;
- }
- }
- return rePath;
- }
- public static String makeDirByParamForOdsRealPath(String jobNumberold,String type){
- String jobNumber=jobNumberold.trim();
- String rePath="";
- if(jobNumber==null||jobNumber.trim().equals("")){
- }else{
- if(type==BlobUtil.DirTypeTempupload){
- File tempUploadFile=new File(BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber);
- if(!tempUploadFile.exists()){
- tempUploadFile.mkdir();
- }
- rePath="\\\\tempupload\\\\"+jobNumber+"\\\\"+jobNumber;
- }else if(type==BlobUtil.DirTypeOdsuser){
- File tempUploadFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+jobNumber);
- if(!tempUploadFile.exists()){
- tempUploadFile.mkdir();
- }
- rePath="\\\\odsuser\\\\"+jobNumber+"\\\\"+jobNumber;
- }else if(type==BlobUtil.DirTypeTempuser){
- File tempUploadFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+jobNumber);
- if(!tempUploadFile.exists()){
- tempUploadFile.mkdir();
- }
- rePath="\\\\tempuser\\\\"+jobNumber+"\\\\"+jobNumber;
- }
- }
- return rePath;
- }
- public static String changeFileName(String fullold,String filename,String newname){
- String res="";
- String a=filename.substring(0,filename.lastIndexOf("."));
- String b=BlobUtil.getFileSuffix(filename);
- res=fullold.replaceAll(filename, newname+b);
- return res;
- }
- public static void main(String[] ss){
- String serverLocalPath=BlobUtil.BASE_PATH+"/gg/gg.jpg".replaceAll("/", "\\\\");
- System.out.println("BASE_PATH::"+BlobUtil.BASE_PATH);
- System.out.println("WEBCONTENT_PATH::"+BlobUtil.WEBCONTENT_PATH);
- System.out.println("TEMP_UPLOAD_PATH::"+BlobUtil.TEMP_UPLOAD_PATH);
- System.out.println("ODSUSER_PHOTO_PATH::"+BlobUtil.ODSUSER_PHOTO_PATH);
- System.out.println("TEMPUSER_PHOTO_PATH::"+BlobUtil.TEMPUSER_PHOTO_PATH);
- String aa="sfs.333.jpgg";
- System.out.println(aa.substring(0,aa.lastIndexOf(".")));
- System.out.println(BlobUtil.changeFileName("as/asd/3.jpg","3.jpg","nn"));
- /*
- BASE_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto
- WEBCONTENT_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent
- TEMP_UPLOAD_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto\tempupload
- ODSUSER_PHOTO_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto\odsuser
- TEMPUSER_PHOTO_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto\tempuser
- */
- }
- }
TempUser.java
- package org.hd.tempuser.model;
- import java.util.Date;
- import java.sql.Blob;
- public class TempUser {
- //import oracle.sql.BLOB;
- private String hduid;
- private String uname;
- private String upass;
- private String realname;
- private String sex;
- private String email;
- private String utype;
- private String cellphone;
- private String ext;
- private String phone;
- private String job_level;
- private String valid;
- private Blob picture;
- private Date create_date;
- private String creator;
- private Date edit_date;
- private String editor;
- private String remark;
- //虚拟字段
- private String tempUrl;//照片url
- private String vjob_level;//职级
- public String getHduid() {
- return hduid;
- }
- public void setHduid(String hduid) {
- this.hduid = hduid;
- }
- public String getUname() {
- return uname;
- }
- public void setUname(String uname) {
- this.uname = uname;
- }
- public String getUpass() {
- return upass;
- }
- public void setUpass(String upass) {
- this.upass = upass;
- }
- public String getRealname() {
- return realname;
- }
- public void setRealname(String realname) {
- this.realname = realname;
- }
- public String getSex() {
- return sex;
- }
- public void setSex(String sex) {
- this.sex = sex;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getUtype() {
- return utype;
- }
- public void setUtype(String utype) {
- this.utype = utype;
- }
- public String getCellphone() {
- return cellphone;
- }
- public void setCellphone(String cellphone) {
- this.cellphone = cellphone;
- }
- public String getExt() {
- return ext;
- }
- public void setExt(String ext) {
- this.ext = ext;
- }
- public String getPhone() {
- return phone;
- }
- public void setPhone(String phone) {
- this.phone = phone;
- }
- public String getJob_level() {
- return job_level;
- }
- public void setJob_level(String job_level) {
- this.job_level = job_level;
- }
- public String getValid() {
- return valid;
- }
- public void setValid(String valid) {
- this.valid = valid;
- }
- public Blob getPicture() {
- return picture;
- }
- public void setPicture(Blob picture) {
- this.picture = picture;
- }
- public Date getCreate_date() {
- return create_date;
- }
- public void setCreate_date(Date create_date) {
- this.create_date = create_date;
- }
- public String getCreator() {
- return creator;
- }
- public void setCreator(String creator) {
- this.creator = creator;
- }
- public Date getEdit_date() {
- return edit_date;
- }
- public void setEdit_date(Date edit_date) {
- this.edit_date = edit_date;
- }
- public String getEditor() {
- return editor;
- }
- public void setEditor(String editor) {
- this.editor = editor;
- }
- public String getRemark() {
- return remark;
- }
- public void setRemark(String remark) {
- this.remark = remark;
- }
- public String getTempUrl() {
- return tempUrl;
- }
- public void setTempUrl(String tempUrl) {
- this.tempUrl = tempUrl;
- }
- public String getVjob_level() {
- return vjob_level;
- }
- public void setVjob_level(String vjob_level) {
- this.vjob_level = vjob_level;
- }
- }
TempUser.hbm.xml
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="org.hd.tempuser.model.TempUser" table="hd_user">
- <id name="hduid" type="java.lang.String">
- <column name="hduid" length="32" />
- <generator class="assigned" />
- </id>
- <property name="uname" type="java.lang.String">
- <column name="uname" length="50">
- </column>
- </property>
- <property name="upass" type="java.lang.String">
- <column name="upass" length="100" />
- </property>
- <property name="realname" type="java.lang.String">
- <column name="realname" length="50">
- </column>
- </property>
- <property name="sex" type="java.lang.String">
- <column name="sex" length="50" />
- </property>
- <property name="email" type="java.lang.String">
- <column name="email" length="100">
- </column>
- </property>
- <property name="utype" type="java.lang.String">
- <column name="utype" length="10" />
- </property>
- <property name="cellphone" type="java.lang.String">
- <column name="cellphone" length="50">
- </column>
- </property>
- <property name="ext" type="java.lang.String">
- <column name="ext" length="50" />
- </property>
- <property name="phone" type="java.lang.String">
- <column name="phone" length="50" />
- </property>
- <property name="job_level" type="java.lang.String">
- <column name="job_level" length="50" />
- </property>
- <property name="valid" type="java.lang.String">
- <column name="valid" length="10" />
- </property>
- <property name="picture" type="java.sql.Blob">
- <column name="picture" />
- </property>
- <property name="create_date" type="java.util.Date">
- <column name="create_date" />
- </property>
- <property name="creator" type="java.lang.String">
- <column name="creator" length="32" />
- </property>
- <property name="edit_date" type="java.util.Date">
- <column name="edit_date" />
- </property>
- <property name="editor" type="java.lang.String">
- <column name="editor" length="32" />
- </property>
- <property name="remark" type="java.lang.String">
- <column name="remark" length="200" />
- </property>
- </class>
- </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[]类型!
- /**
- * 增加用户,把照片从临时的上传目录下写入数据库Blob
- */
- public void addTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
- String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
- IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
- .getComponent(IKeyGen.BEAN_ID);
- String Id = keyService.getUUIDKey();
- tempUser.setHduid(Id);
- //默认字段
- tempUser.setCreate_date(new Date());
- tempUser.setCreator(loginUserJobNum);
- try {
- tempUser.setPicture(BLOB.empty_lob());
- } catch (SQLException e2) {
- e2.printStackTrace();
- }
- Session s=this.getSessionFactory().openSession();
- Transaction t = s.beginTransaction();
- s.save(tempUser);
- s.flush();
- s.refresh(tempUser,LockMode.UPGRADE); //锁定为更新模式
- try{
- File uploadFile=new File(serverLocalPath);
- FileInputStream fis = new FileInputStream(uploadFile);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] b = new byte[1024];
- int n;
- while ((n=fis.read(b)) != -1) {
- out.write(b,0,n);
- }
- fis.close();
- out.close();
- byte[] content = out.toByteArray();
- tempUser.setPicture(Hibernate.createBlob(content));
- s.flush();
- t.commit();
- s.close();
- }
- catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
编辑用户时,需要先把数据库的Blob字段置空null,然后再更新(不知有没有其他直接更新的方法)
所以在action我先tempUserService.clearPhotoBlob(getEditTempUser());
- public void clearPhotoBlob(TempUser tempUser){
- String nasql="update hd_user g set g.picture=null " +
- " where g.hduid='"+tempUser.getHduid().trim()+"' ";
- this.createNativeSQL(nasql);
- }
然后再更新blob,
tempUserService.editTempUserWriteBlob(getEditTempUser(),
getLocalPhotoUrl(), loginUserJobNum);
- /**
- * 编辑用户,把照片从临时的上传目录下写入数据库Blob
- */
- public void editTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
- String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
- //默认字段
- tempUser.setCreate_date(new Date());
- tempUser.setCreator(loginUserJobNum);
- try {
- tempUser.setPicture(BLOB.empty_lob());
- } catch (SQLException e2) {
- e2.printStackTrace();
- }
- // String nasql="update hd_user g set g.picture=null " +
- // " where g.hduid='"+tempUser.getHduid().trim()+"' ";
- // this.createNativeSQL(nasql);
- Session s=this.getSessionFactory().openSession();
- Transaction t = s.beginTransaction();
- tempUser.setPicture(Hibernate.createBlob(new byte[1]));
- s.saveOrUpdate(tempUser);
- s.flush();
- s.refresh(tempUser,LockMode.UPGRADE); //锁定为更新模式
- try{
- File uploadFile=new File(serverLocalPath);
- FileInputStream fis = new FileInputStream(uploadFile);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] b = new byte[1024];
- int n;
- while ((n=fis.read(b)) != -1) {
- out.write(b,0,n);
- }
- fis.close();
- out.close();
- byte[] content = out.toByteArray();
- tempUser.setPicture(Hibernate.createBlob(content));
- s.flush();
- t.commit();
- s.close();
- }
- catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
至于读取Blob,你只需要先读取出来放到服务器下某个路径,然后返回这个路径用于页面展示。
例如,在查看用户信息的时候,需要展示照片。
- //读取TempUser照片信息
- public String getTempPhoto(TempUser tempUser){
- String resPath="";
- if(tempUser==null){
- }else if(tempUser.getPicture()==null){
- }else{
- Blob blob=(Blob)tempUser.getPicture();
- resPath=BlobUtil.makeLocalPhoto(blob, tempUser.getUname(), true);
- }//end else
- return resPath;
- }
其中
- public static String makeLocalPhoto(Blob blob,String tergetDirName,boolean isTempUser){
- String relativepath="";
- tergetDirName=tergetDirName.trim();
- if(blob==null){
- System.out.println("无法读取图片信息!");
- }else{
- if(tergetDirName==null||tergetDirName.trim().equals("")){
- System.out.println("无法获取工号创建目录!");
- }else{
- if(isTempUser){//临时长期用户
- File tempFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+tergetDirName);
- if(!tempFile.exists()){
- tempFile.mkdir();
- }
- boolean falg=blobToPhoto(blob,tempFile,tergetDirName);
- if(falg){
- relativepath="/tempphoto/tempuser/"+tergetDirName+"/"+tergetDirName+".jpg";
- }else{
- }
- }else{//ods用户
- File odsFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+tergetDirName);
- if(!odsFile.exists()){
- odsFile.mkdir();
- }
- boolean falg=blobToPhoto(blob,odsFile,tergetDirName);
- if(falg){
- relativepath="/tempphoto/odsuser/"+tergetDirName+"/"+tergetDirName+".jpg";
- }else{
- }
- }
- }
- }//end else
- return relativepath;
- }
其中
- public static boolean blobToPhoto(Blob blob,File tergetDirFile,String tergetDirName){
- String photoPath=tergetDirFile.getPath().trim();
- boolean issuccess=true;
- if(!tergetDirFile.exists()){
- System.out.println("目标路径不存在"+tergetDirFile.getPath());
- issuccess=false;
- }else if(!tergetDirFile.isDirectory()){
- System.out.println("目标路径不是目录"+tergetDirFile.getPath());
- issuccess=false;
- }else{
- File photo=new File(photoPath+"\\"+tergetDirName.trim()+".jpg");
- FileOutputStream fos = null;
- InputStream is = null;
- byte[] Buffer = new byte[4096];
- try {
- is=blob.getBinaryStream();
- fos=new FileOutputStream(photo);
- int size = 0;
- while ((size = is.read(Buffer)) != -1) {
- fos.write(Buffer, 0, size);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- try {
- if (fos != null) {
- fos.flush();
- fos.close();
- }
- if (is != null) {
- is.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }//end else
- return issuccess;
- }
这里读出来的图片都是.jpg格式的,因为后缀我写死了,这里还不完善。
注意:你需要传入已经上传到服务器的文件的地址,这个用个工具类实现BlobUtil.java。
这样管理比较清晰。
上传图片至服务器,写入到数据库Blob字段中,以及从数据库读取Blob信息(iframe父子页面传值)(2)相关推荐
- 上传图片至服务器,写入到数据库Blob字段中,以及从数据库读取Blob信息(iframe父子页面传值)(1)
最近做了个用户维护功能,涉及到照片的操作. 照片是存到数据库oracle中的Blob字段中. 难点有两个: 1,图片的上传:2,Blob字段的读取. 先说图片的上传吧, 我使用common-fileu ...
- delphi mysql dll直接_十万火急!!!那位高手用过libmysql.dll直接连接MySql数据库?如何将二进制文件保存到blob字段中? (60分)...
先用php+mysql将文件通过web方式保存到远程的服务器的blob字段中,然后用 delphi+libmysql.dll直接连接远程MySql数据库,再将数据复制到本地的MySql数据库中. 代码 ...
- 图片上传到数据库,保存到Blob字段中
需求:从系统上传图片,将图片信息保存到数据库的blob字段中,并提供照片的查询接口 controller: package com.success.controller;import ../*** 系 ...
- 将页面多个下拉框的值以字符串拼接方式存放至数据库一个字段中
1,当页面中有多个值,传入Controller并以字符串拼接方式,以","隔开存放至数据库一个字段中,页面中多个<select name="off"&g ...
- Java中对查出的数据计数_基础算法7:从数据库某个字段中取出现次数最多的几条数据形成“热门xxx”...
在这里,我们需要查出所有的"出发城市"和"到达城市",并对每个城市进行计数根据其出现次数来取出几个出现次数最多的城市为热门城市 注:将多个字段的数据合并在一起并 ...
- 如何使用SQL批量替换数据库特定字段中部分特定数据
1.替换数据库特定字段中部分特定数据的SQL语句 SQL语句:update 表名 set 字段名= replace(字段名,'原字符串',需要替换成的字符串') 以将表exam_major中的字段po ...
- cmd查看mysql数据库表_cmd中查看MySQL数据库表数据及结构
0. 1 .cmd进入mysql安装的bin目录(C:\Program Files\XXXXXX\MySQL Server 5.6\bin) mysql -hlocalhost -uroot -p 回 ...
- 用python将中文/汉字写入文本文档或者从文本文档读取中文信息
用python将中文/汉字写入文本文档或者从文本文档读取中文信息 经常有同学碰到通过python无法将汉字信息写入文本,或者无法读取文本里的汉字信息的情况,下面用一种最简单的方式解决这个问题. 写入文 ...
- oracle blob字段索引,在oracle 数据库中使用 Blob 字段存储 一张图片并读取
1. 进行数据库的设置 create table image_lob(t_id varchar2(5) not null,t_image blob not null); create or repl ...
最新文章
- Oracle 基础练习
- 将枚举值转换为DropDownList等的选项值
- 怎么在vue的@click里面直接写js_【转】为 Node.js 贡献你的力量 ———— 调试代码
- 解决因删除外键引用的时候导致相应字段被删除了的问题
- YbtOJ#652-集合比较【Treap】
- win8信息服务器不可用怎么办,win8系统下开机提示OneDrive选项此服务现在不可用请稍后再试怎么办...
- 周围剃光头顶留长发型_?22岁亿万富翁凯莉登杂志,顶着5斤“鸟窝头”凹造型,绝代艳后...
- Latex 图像总是出现在目标页的下一页置顶
- 《逆袭进大厂》之C++篇49问49答(绝对的干货)
- StructureMap 作为 ASP.NET MVC 的 DI 框架的使用实例
- Android-7.0-Nuplayer-启动流程
- 判刑不应区分未成年、精神病
- 冰点还原离线激活_冰点还原密钥,小编教你如何激活冰点还原
- 华为云PBX_基于华为云客服平台打造的比特百灵鸟AI管家解决方案发布
- java 加密 —— 对称加密、非对称加密、消息摘要
- HTML与Java组合使用_【自学java笔记#第五十四天#】javaweb day02 html和css的组合使用...
- Leecode第九天,广度优先搜索之矩阵,腐烂的橘子
- python读取文件r_python读入文件时加r的作用?
- Atom编译器64位win版本下载汉化及前端必备插件
- UE4蓝图案例:媒体播放器的开关1
热门文章
- list python 访问 键值对_学完Python,我决定熬夜整理这篇总结...
- 在URP中使用UICamera
- unity Mirror使用笔记
- android java写文件_Android中文件的读写(一)----流操作
- 使用绑定进行WPF DataGrid格式化的指南
- 什么是数据库触发器?
- java正则获取数字_Java通过正则表达式获取字符串中数字的方法示例
- python string.format()_python string format
- 石头剪刀布python代码_Python实现的石头剪子布代码分享
- Django 报错 ‘polls‘ is not a registered namespace