您的位置:首页 > 编程语言 > Java开发

用Java或Jsp向数据库存取二进制图片

2012-08-09 14:50 344 查看
前几天突然看到学校音乐站上的图片原来是存储在数据库上的,是二进制而不是使用路径保存的,在网上招了找发现大多介绍的都是hph方式,在这里做个总结,首先要存储二进制文件在数据库中要搞清楚下面几个内容:

  1 MySQL存储大容量的二进制文件的格式是blob,其实除了图片还可以存别的

  2 要向数据库存储二进制的文件一定要把要存储的数据转换成二进制流

  废话就不多说了,大家看看代码很容易明白,先来看一个app程序,当然首先您要在数据库中先建立一个用于保存图片的表和相应的列,数据格式为blob

源码复制打印?

  package com.lizhe;
  import Java.io.*;
  import java.sql.*;
  public class PutImg {
  public void putimg() {
  try {
  Class.forName("org.gjt.mm.mysql.Driver").newInstance();
  String url = "JDBC:mysql://localhost/img?user=root&password=root&useUnicode=true&characterEncoding=gbk";
  Connection conn = DriverManager.getConnection(url);
  Statement stmt = conn.createStatement();
  //stmt.execute("insert into imgt (id) values (5)");

  stmt.close();
  PreparedStatement pstmt = null;
  String sql = "";
  File file = new File("c:log.jpg");
  InputStream photoStream = new FileInputStream(file);
  //sql = " UPDATE imgt SET img = ? ";

  sql = "INSERT INTO imgtable (img) VALUES (?)";
  pstmt = conn.prepareStatement(sql);
  pstmt.setBinaryStream(1, photoStream, (int) file.length());
  pstmt.executeUpdate();
  pstmt.close();
  conn.close();
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
  public static
void main(String args[]){
  PutImg pi=new PutImg();
  pi.putimg();
  }
  }

源码复制打印?

 InputStream photoStream = new FileInputStream(file);

 InputStream photoStream = new FileInputStream(file);


  可以很清楚的看到我们首先把一个图片文件(当然也可以是别的什么文件)转换成了一个二进制输入流

源码复制打印?

 pstmt.setBinaryStream(1, photoStream, (int) file.length());

源码复制打印?

package com.lizhe;
  import Java.io.*;
  import java.sql.*;
  class GetImg {
  private
static final String URL = "JDBC:MySQL://localhost/img?user=root&password

  =root&useUnicode=true&characterEncoding=gbk";
  private Connection conn =
null;
  private PreparedStatement pstmt =
null;
  private ResultSet rs =
null;
  private File file =
null;
  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 = DriverManager.getConnection(URL);
  pstmt = conn.prepareStatement("select img from imgt 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("img");
  int size = 0;
  while ((size = is.read(Buffer)) != -1) {
  // System.out.println(size);
  fos.write(Buffer, 0, size);
  }
  } catch (Exception e) {
  System.out.println( e.getMessage());
  } finally {
  // 关闭用到的资源
  fos.close();
  rs.close();
  pstmt.close();
  conn.close();
  }
  }
  public static
void main(String[] args) {
  try {
  GetImg gi=new GetImg();
  gi.blobRead("c:/getimgs/1.jpg",
5);
  } catch (Exception e) {
  System.out.println("[Main func error: ]" + e.getMessage());
  }
  }
  }

package com.lizhe;
  import Java.io.*;
  import java.sql.*;
  class GetImg {
  private static final String URL = "JDBC:MySQL://localhost/img?user=root&password
  =root&useUnicode=true&characterEncoding=gbk";
  private Connection conn = null;
  private PreparedStatement pstmt = null;
  private ResultSet rs = null;
  private File file = null;
  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 = DriverManager.getConnection(URL);
  pstmt = conn.prepareStatement("select img from imgt 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("img");
  int size = 0;
  while ((size = is.read(Buffer)) != -1) {
  // System.out.println(size);
  fos.write(Buffer, 0, size);
  }
  } catch (Exception e) {
  System.out.println( e.getMessage());
  } finally {
  // 关闭用到的资源
  fos.close();
  rs.close();
  pstmt.close();
  conn.close();
  }
  }
  public static void main(String[] args) {
  try {
  GetImg gi=new GetImg();
  gi.blobRead("c:/getimgs/1.jpg", 5);
  } catch (Exception e) {
  System.out.println("[Main func error: ]" + e.getMessage());
  }
  }
  }


  这里需要注意的是

源码复制打印?

 is = rs.getBinaryStream("img");

源码复制打印?

/*
  * Generated by MyEclipse Struts
  * Template path: templates/Java/JavaClass.vtl

  */
  package com.lizhe.struts.action;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.IOException;
  import java.io.InputStream;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  import java.sql.Statement;
  import javax.Servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import org.apache.struts.action.Action;
  import org.apache.struts.action.ActionForm;
  import org.apache.struts.action.ActionForward;
  import org.apache.struts.action.ActionMapping;
  import org.apache.struts.upload.FormFile;
  import com.lizhe.struts.form.UpimgForm;
  /**
  * MyEclipse Struts
  * Creation date: 05-18-2007

  *
  * XDoclet definition:
  * @struts.action path="/upimg" name="upimgForm" input="/userhomepage.JSP"

  * @struts.action-forward name="userhome" path="/userhomepage.jsp" redirect="true" contextRelative="true"

  */
  public class UpimgAction
extends Action {
  /*
  * Generated Methods
  */
  /**
  * Method execute
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  * @throws IOException
  * @throws FileNotFoundException

  */
  public ActionForward execute(ActionMapping mapping, ActionForm form,
  HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
  UpimgForm upimgForm = (UpimgForm) form;// TODO Auto-generated method stub

  FormFile file=upimgForm.getFile();
  InputStream is=file.getInputStream();
  try {
  Class.forName("org.gjt.mm.MySQL.Driver").newInstance();
  String url = "JDBC:mysql://localhost/blog?user=root&password=root&useUnicode=true&characterEncoding=gb2312";
  Connection conn = DriverManager.getConnection(url);
  Statement stmt = conn.createStatement();
  //stmt.execute("insert  into  img (id)  values  (5)");

  stmt.close();
  PreparedStatement pstmt = null;
  String sql = "";
  //File file = new File("c:log.jpg");

  //InputStream photoStream = new FileInputStream(file);

  //sql = "  UPDATE  imgt  SET  img  =  ?  ";

  sql = "INSERT INTO img (img) VALUES (?)";
  pstmt = conn.prepareStatement(sql);
  pstmt.setBinaryStream(1, is, (int) file.getFileSize());
  pstmt.executeUpdate();
  pstmt.close();
  conn.close();
  } catch (Exception e) {
  e.printStackTrace();
  }
  return mapping.findForward("userhomepage");
  }
  }

/*
  * Generated by MyEclipse Struts
  * Template path: templates/Java/JavaClass.vtl
  */
  package com.lizhe.struts.action;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.IOException;
  import java.io.InputStream;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  import java.sql.Statement;
  import javax.Servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import org.apache.struts.action.Action;
  import org.apache.struts.action.ActionForm;
  import org.apache.struts.action.ActionForward;
  import org.apache.struts.action.ActionMapping;
  import org.apache.struts.upload.FormFile;
  import com.lizhe.struts.form.UpimgForm;
  /**
  * MyEclipse Struts
  * Creation date: 05-18-2007
  *
  * XDoclet definition:
  * @struts.action path="/upimg" name="upimgForm" input="/userhomepage.JSP"
  * @struts.action-forward name="userhome" path="/userhomepage.jsp" redirect="true" contextRelative="true"
  */
  public class UpimgAction extends Action {
  /*
  * Generated Methods
  */
  /**
  * Method execute
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  * @throws IOException
  * @throws FileNotFoundException
  */
  public ActionForward execute(ActionMapping mapping, ActionForm form,
  HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
  UpimgForm upimgForm = (UpimgForm) form;// TODO Auto-generated method stub
  FormFile file=upimgForm.getFile();
  InputStream is=file.getInputStream();
  try {
  Class.forName("org.gjt.mm.MySQL.Driver").newInstance();
  String url = "JDBC:mysql://localhost/blog?user=root&password=root&useUnicode=true&characterEncoding=gb2312";
  Connection conn = DriverManager.getConnection(url);
  Statement stmt = conn.createStatement();
  //stmt.execute("insert  into  img (id)  values  (5)");
  stmt.close();
  PreparedStatement pstmt = null;
  String sql = "";
  //File file = new File("c:log.jpg");
  //InputStream photoStream = new FileInputStream(file);
  //sql = "  UPDATE  imgt  SET  img  =  ?  ";
  sql = "INSERT INTO img (img) VALUES (?)";
  pstmt = conn.prepareStatement(sql);
  pstmt.setBinaryStream(1, is, (int) file.getFileSize());
  pstmt.executeUpdate();
  pstmt.close();
  conn.close();
  } catch (Exception e) {
  e.printStackTrace();
  }
  return mapping.findForward("userhomepage");
  }
  }


  和app的方式几乎是一样的

  第二个文件是通过jsp将数据库中的图片显示在页面上

  这个有些不同

 

 

源码复制打印?

< %@  page  contentType="text/html;charset=gb2312"%>
  < %@  page  import="java.sql.*"  %>
  < %@  page  import="java.util.*"%>
  < %@  page  import="java.text.*"%>
  < %@  page  import="java.io.*"%>
  < %@  page  import="java.awt.*"%>
  < html>
  < body>
  < %
  Class.forName("org.gjt.mm.mysql.Driver").newInstance();
  String url="jdbc:mysql://localhost/img?user=root&password=root";
  Connection  con  =  DriverManager.getConnection(url);
  String  sql  =  "select  *  from imgt where id=5";
  Statement stmt = con.createStatement();
  ResultSet rs = stmt.executeQuery(sql);
  if(rs.next()) {
  InputStream in = rs.getBinaryStream("img");
  ServletOutputStream op = response.getOutputStream();
  int len;
  byte[] buf=new
byte[1024];
  while((len= in.read(buf))!=-1) {
  op.write(buf, 0, len);
  }
  op.close();
  in.close();
  }
  rs.close();
  stmt.close();
  con.close();
  %>
  < /body>
  < /html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: