向数据库插入图片以及从数据库中读取图片并显示到jsp(数据库中存储的图片字段类型为Blob或image)...

以前都是将图片的存储路径存在数据库中,这次学习了将图片以blob类型或image类型存储在数据库中,并从数据库中获取图片显示到jsp中。

表名为:tmp(员工表)

字段:id (员工id,int类型),pic(员工照片,blob类型),descs(照片文件名,varchar类型)

java bean类可以直接用Blob类型的属性接收pic字段,如Tmp类中有属性:private Blob photo;(也可以是其它类型,转换一下就OK)

下面是用struts2实现的读取图片并显示到jsp的代码,直接把方法写在Action中, 由于使用到response,一定要实现接口ServletResponseAware并实现setServletResponse方法, 否则response会报空指针异常。 struts2的上传图片并插入数据库方法还没写,以后整理。。。

public class ImageAction extends ActionSupport implements ServletResponseAware{
    private static final String URL = "jdbc:mysql://localhost:3306/test?user=root&password=qweqwe1314&useUnicode=true";
    private Connection conn = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs = null;
    private int picID = 1;
    private ServletOutputStream sout;

    private HttpServletResponse response;

    public String execute() throws Exception {
        Class.forName("org.gjt.mm.mysql.Driver").newInstance();
        conn = (Connection) DriverManager.getConnection(URL);
        pstmt = (PreparedStatement) conn
                .prepareStatement("select pic from tmp where id=?");
        pstmt.setInt(1, picID); // 传入要取的图片的ID
        rs = pstmt.executeQuery();
        if (rs.next()) {
            Blob photo = (Blob) rs.getBlob("pic");
            InputStream in = photo.getBinaryStream();
            response.reset();
            sout = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = in.read(b);
            while (len != -1) {
                sout.write(b);
                len = in.read(b);
            }
            sout.flush();
            sout.close();
            in.close();
        }
        return "success";
    }

    public ServletOutputStream getSout() {
        return sout;
    }

    public void setSout(ServletOutputStream sout) {
        this.sout = sout;
    }

    @Override
    public void setServletResponse(HttpServletResponse arg0) {
        // TODO Auto-generated method stub
        this.response = arg0;
    }

}

jsp只需用img标签,src为${sout}就可以将图片显示出来: <img src="${sout}"/>

 

以下是没有用struts2的两个方法, 分别是向数据库存入一张图片,从数据库读取一张图片

package com.image;

import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.ResultSet;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class BlobPros {
    private static final String URL = "jdbc:mysql://localhost:3306/test?user=root&password=qweqwe1314&useUnicode=true";
    private Connection conn = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs = null;
    private File file = null;

    public BlobPros() {
    }

    /**
     * 向数据库中插入一个新的BLOB对象(图片)
     * 
     * @param infile
     *            要输入的数据文件
     * @throws java.lang.Exception
     */
    public void blobInsert(String infile) throws Exception {
        FileInputStream fis = null;
        try {
            Class.forName("org.gjt.mm.mysql.Driver").newInstance();
            conn = (Connection)DriverManager.getConnection(URL);

            file = new File(infile);
            fis = new FileInputStream(file);
            // InputStream fis = new FileInputStream(infile);
            pstmt = (PreparedStatement)conn.prepareStatement("insert into tmp(descs,pic) values(?,?)");
            pstmt.setString(1, file.getName()); // 把传过来的第一个参数设为文件名
            // pstmt.setBinaryStream(2,fis,(int)file.length());
            // //这种方法原理上会丢数据,因为file.length()返回的是long型
            pstmt.setBinaryStream(2, fis, fis.available()); // 第二个参数为文件的内容
            pstmt.executeUpdate();
        } catch (Exception ex) {
            System.out.println("[blobInsert error : ]" + ex.toString());
        } finally {
            // 关闭所打开的对像//
            pstmt.close();
            fis.close();
            conn.close();
        }
    }

    /**
     * 从数据库中读出BLOB对象
     * 
     * @param outfile
     *            输出的数据文件
     * @param picID
     *            要取的图片在数据库中的ID
     * @throws java.lang.Exception
     */

    public void blobRead(String outfile, int picID) throws Exception {
        FileOutputStream fos = null;
        InputStream is = null;
        byte[] Buffer = new byte[4096];

        try {
            Class.forName("org.gjt.mm.mysql.Driver").newInstance();
            conn = (Connection)DriverManager.getConnection(URL);
            pstmt = (PreparedStatement)conn.prepareStatement("select pic from tmp where id=?");
            pstmt.setInt(1, picID); // 传入要取的图片的ID
            rs = pstmt.executeQuery();
            rs.next();

            file = new File(outfile);
            if (!file.exists()) {
                file.createNewFile(); // 如果文件不存在,则创建
            }
            fos = new FileOutputStream(file);
            is = rs.getBinaryStream("pic");
            int size = 0;
            /*
             * while(size != -1) { size = is.read(Buffer); //从数据库中一段一段的读出数据
             * //System.out.println(size); if(size != -1) //-1表示读到了文件末
             * fos.write(Buffer,0,size); }
             */
            while ((size = is.read(Buffer)) != -1) {
                // System.out.println(size);
                fos.write(Buffer, 0, size);
            }

        } catch (Exception e) {
            System.out.println("[OutPutFile error : ]" + e.getMessage());
        } finally {
            // 关闭用到的资源
            fos.close();
            rs.close();
            pstmt.close();
            conn.close();
        }
    }

    public static void main(String[] args) {
        try {

            BlobPros blob = new BlobPros();
            //blob.blobInsert("e:/llj/1.jpg");
            // blob.blobInsert("C:Downloadsluozsh1.jpg");
            blob.blobRead("e:/llj/2.jpg", 1);
        } catch (Exception e) {
            System.out.println("[Main func error: ]" + e.getMessage());
        }
    }
}

 

转载于:https://www.cnblogs.com/xiaomimi/archive/2012/09/04/2669955.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用JSPJava代码从数据库读取图片并将其显示在网页上。以下是一些步骤: 1. 在数据库创建一个BLOB类型字段,用于存储图片的二进制数据。 2. 将图片转换为字节数组并将其保存到数据库。您可以使用Java的FileInputStream和ByteArrayOutputStream类来完成此操作。 3. 在JSP页面,使用Java代码从数据库检索图像数据。您可以使用JDBC API的ResultSet类来检索数据。 4. 将字节数组转换为图像,并将其显示在网页上。您可以使用JavaImageIO类来完成此操作。 下面是一个简单的示例代码,它演示了如何从数据库读取图像并将其显示JSP页面上: ``` <%@page import="java.sql.*"%> <%@page import="java.io.*"%> <%@page import="javax.imageio.*"%> <%@page import="javax.servlet.http.*"%> <% // 获取图像ID int imageId = Integer.parseInt(request.getParameter("imageId")); // 从数据库检索图像数据 byte[] imageData = null; try { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "myuser", "mypassword"); PreparedStatement stmt = conn.prepareStatement("SELECT image_data FROM images WHERE image_id = ?"); stmt.setInt(1, imageId); ResultSet rs = stmt.executeQuery(); if (rs.next()) { imageData = rs.getBytes("image_data"); } rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } // 将字节数组转换为图像 BufferedImage image = null; try { ByteArrayInputStream bis = new ByteArrayInputStream(imageData); image = ImageIO.read(bis); } catch (IOException e) { e.printStackTrace(); } // 在网页上显示图像 response.setContentType("image/jpeg"); OutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); out.close(); %> ``` 在上面的示例,我们从请求参数获取图像ID,并使用JDBC API从数据库检索图像数据。然后,我们将图像数据转换为图像,并将其入响应流,以便在网页上显示。请注意,我们将响应类型设置为“image/jpeg”,因为我们使用的是JPEG格式的图像。如果您使用的是其他格式的图像,请相应地更改响应类型

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值