blob存取数据库

将图片以blob存入数据库

public String uploadfile() {
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = ServletActionContext.getRequest();
            String path = request.getContextPath();
            Blob photo = null;
            String basePath = request.getScheme() + "://"+ request.getServerName() + path + "/";   
            String filename = getNum();           
            //判断是否为图片 
            if(isImage(myFile)){  // File类型
              
            }else{             
               return ERROR;
            }
            filename += ".png";
            Photolist pl = new Photolist();
            FileInputStream fis = new FileInputStream(myFile);
            photo = Hibernate.createBlob(fis);   // org.hibernate.Hibernate

            pl.setImagefile(photo);
            pl.setAddtime(new Date());
            pl.setName(filename);
            service.save(pl);           
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

public  boolean isImage(File imageFile) { 
        if (!imageFile.exists()) { 
            return false; 
        } 
        Image img = null;  // java.awt.Image

        try { 
            img = ImageIO.read(imageFile);   // javax.imageio.ImageIO

            if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) { 
                return false; 
            } 
            return true; 
        } catch (Exception e) { 
            return false; 
        } finally { 
            img = null; 
        } 
    } 

从数据库中读出blob

public String getImageFile() {
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = ServletActionContext.getRequest();
            String pid = request.getParameter("pid");           
            ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();          
            Photolist pl = new Photolist();
            pl = (Photolist) service.get(Photolist.class, Long.parseLong(pid));
            int len = 0;
            Blob blob = pl.getImagefile();  //该字段类型为Blob
            InputStream input = blob.getBinaryStream();
            byte[] image = new byte[(int) blob.length()];
            while ((len = input.read(image)) != -1) {
                out.write(image, 0, len);
            }
            out.flush();
            out.close();
        } catch (IOException e) {         
            e.printStackTrace();
        } catch (SQLException e) {           
            e.printStackTrace();
        }
        return null;
    }

页面上图片的显示:

<img width="70" height="70" src="/pay/private/izone/authentication/getImageFile.action?pid=1281970" />

猜你喜欢

转载自bingdongsanxian.iteye.com/blog/2253094