图片保存到数据库blob字段

来源:互联网 发布:unity3d guitexture 编辑:程序博客网 时间:2024/05/29 18:18

前言

目前个人总结图片保存有三种方式:
1.大型有关图片的项目一般都是保存到一个第三方的云服务器上,数据库保存图片的地址就可以了。
2.也可以将图片上传到自己项目所在的服务器上,数据库保存图片的地址就可以了。
3.第三种就是将图片保存到数据库的blob字段里。
今天主要说第三种方式。

图片保存

dao层代码如下:

public void doSave(Map<String, Object> parasMap) throws Exception {        StringBuffer sql = new StringBuffer();        Connection conn = null;        PreparedStatement pst = null;        try{            conn = this.getConnection();            sql.append("insert into picture_t  ");            sql.append("(id,name,picture)   ");            sql.append("values(picture_s.nextval,'"+parasMap.get("name")+"',?)  ");            pst = conn.prepareStatement(sql.toString());            File file =  new File(parasMap.get("src"));            FileInputStream fStream = new FileInputStream(file);            pst.setBinaryStream(1, fStream, (int) file.length());            pst.execute();        }catch(Exception e){            System.out.pring(e);        }finally{            close(pst,conn);        }}

上边的代码中可以看到,参数parasMap中包含图片的路径(parasMap.get(“src”)),将图片路径利用文件输入流读取图片保存到数据库中,数据库中picture字段就是blob类型。

图片读取展现到页面

dao层代码正常写,从数据库select图片所在的blob字段,用rs.getBlob(“picture”)获取并保存到Map中然后添加到list中即可。
action中接收到该list后做如下处理:

public void queryImg(HttpServletRequest request,            HttpServletResponse response) throws Exception{        String id = request.getParameter("id");        String imgIndex = request.getParameter("imgIndex");        List<Map<String,Object>>  list =  bo.queryImgById(id);        Blob blob=(Blob) list.get( Integer.parseInt(imgIndex)).get("picture");        int length = (int) blob.length();        byte[] bImage = new byte[length];        InputStream is = new BufferedInputStream(blob.getBinaryStream());        is.read(bImage, 0, length);        OutputStream out = response.getOutputStream();         out.write(bImage);        out.flush();         out.close();        is.close();    }

上边的代码中可以看出将图片从list里取出来后强转为Blob类型,这个类型是java自带的类。
页面的img标签的src要请求到这个方法中,如下:

<img src="/picture.do?method=queryImg&id=1&imgIndex=2">

注意事项

以上方法就可以将图片保存到数据库并回显到页面上。难点在于如何同时处理多张图片。对于保存来说就是写个循环保存即可,而对于回显来说,就要先写一个方法,查询一共有多少张图片回显,比如有3张图片,那么在页面上就要有三个
<img src="/picture.do?method=queryImg&id=1&imgIndex=2">
每个img标签的不同之处在于向后端传的参数imgIndex,分别为0、1、2,
这样就可以同时回显3张图片了。

阅读全文
0 0