java中將圖片保存到數據庫中

在實際的開發中,咱們可能須要將圖片、影音等文件直接保存到數據庫中,而後經過編程方式將數據讀出進行使用。例如將讀出的圖片數據顯示出來,將讀出的電影文件播放出來。 二進制數據直接保存到文件和從文件中讀出很是的簡單。和普通的數據庫操做差異不大。只是用到部分流操做。例如各類輸入輸出流操做。因此深入理解流操是很是重要的。 在此我藉助於一個JSP的簡單實例進行講解。此實例保存職員數據,其中職員數據包含一個圖片列。此列保存每名員工的照片。在此將照片直接保存到數據庫中。首先創建職員信息表EmployeeInfo,表列很是的簡單 employeeId:職員編號(自動增加);employeeName:職員姓名;age:職員年齡;pic:職員圖片(image類型) 首先講解信息的保存。先創建一個錄入界面index.jsp,其中包含一個<input type="file"/>元素,用於讓用戶選擇圖片文件。 頁面代碼以下(不作過多講解): < %@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> < % String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> < !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < html> < head> < base href="<%=basePath%>"> < title>My JSP 'index.jsp' starting page</title> < meta http-equiv="pragma" content="no-cache"> < meta http-equiv="cache-control" content="no-cache"> < meta http-equiv="expires" content="0"> < meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> < meta http-equiv="description" content="This is my page"> < !-- <link rel="stylesheet" type="text/css" href="styles.css"> --> < /head> < body> < form action="addServlet" method="POST"> < table border="15" width="60%" align="center"> < tr> < td width="30%" align="right">EmployeeName:</td> < td width="70%" align="left"><input type="text" name="employeeName"/></td> < /tr> < tr> < td width="30%" align="right">Age:</td> < td width="70%" align="left"><input type="text" name="age"/></td> < /tr> < tr> < td width="30%" align="right">Image:</td> < td width="70%" align="left"><input type="file" name="pic"/></td> < /tr> < tr> < td colspan="2" align="center"><input type="submit" value="add"/></td> < /tr> < /table> < /form> < /body> < /html> 頁面請求addServlet,獲取錄入信息,並調用JavaBean實現數據保存。Servlet代碼以下: package com.frank.action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.frank.rule.*; public class AddServlet extends HttpServlet { /** * Constructor of the object. */ public AddServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String employeeName=request.getParameter("employeeName"); int age=Integer.parseInt(request.getParameter("age")); String pic=request.getParameter("pic"); EmployeeDAO employeeDAO=new EmployeeDAO(); if(employeeDAO.employeeAdd(employeeName, age, pic)) response.sendRedirect("success.jsp"); else response.sendRedirect("index.jsp"); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } } 此Servlet只是簡單的獲取頁面輸入的數據,其中獲取的Pic爲用戶選擇的圖片路徑。嚴格講,獲取文件須要通過驗證,防止非法圖片的選擇,這個能夠根據本身的須要改善。而後Servlet調用業務類,將獲取的數據經過參數傳入,進行數據的增長。其中employeeAdd方法實現數據的保存,代碼以下: public boolean employeeAdd(String employeeName,int age,String pic){ Connection conn=null; PreparedStatement pstmt=null; FileInputStream fis=null; try{ Class.forName("net.sourceforge.jtds.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa",""); fis=new FileInputStream(pic); String strSQL="INSERT INTO employeeInfo VALUES(?,?,?)"; pstmt=conn.prepareStatement(strSQL); pstmt.setString(1, employeeName); pstmt.setInt(2, age); pstmt.setBinaryStream(3, fis, fis.available()); if(pstmt.executeUpdate()>0) return true; else return false; }catch(ClassNotFoundException ex){ ex.printStackTrace(); return false; }catch(SQLException ex){ ex.printStackTrace(); return false; }catch(IOException ex){ ex.printStackTrace(); return false; }finally{ try{ fis.close(); pstmt.close(); conn.close(); }catch(Exception ex){ } } } 注意粗體部分,用獲取的pic信息(文件路徑)建立文件輸入流對象,增長pic字段的內容經過流對象增長。 pstmt.setBinaryStream(3, fis, fis.available()); 三個參數分別爲:參數索引,流對象,流對象大小 當增長成功時,重定向到success.jsp 那麼如何驗證圖片數據是否保存到了數據庫中呢?咱們經過再次檢索增長的數據,讀出增長的圖片數據並在頁面中顯示出來進行驗證。 首先創建一個很是簡單的頁面search.jsp,此頁面經過文本框使用戶輸入要檢索的人員的姓名,檢索人員的基本信息(不檢索圖片數據),將檢索的人員數據造成JOPO對象,保存到session中,以便頁面使用。 JOPO類(EmployeeObj) package com.frank.obj; public class EmployeeObj { private int employeeId; private String employeeName; private int age; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } search.jsp頁面代碼以下: < %@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> < % String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> < !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < html> < head> < base href="<%=basePath%>"> < title>My JSP 'search.jsp' starting page</title> < meta http-equiv="pragma" content="no-cache"> < meta http-equiv="cache-control" content="no-cache"> < meta http-equiv="expires" content="0"> < meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> < meta http-equiv="description" content="This is my page"> < !-- <link rel="stylesheet" type="text/css" href="styles.css"> --> < /head> < body> < form action="searchServlet" method="POST"> employeeName:<input type="text" name="employeeName"/> < input type="submit" value="search"/> < /form> < /body> < /html> 經過searchServlet實現基本信息的檢索 package com.frank.action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.frank.obj.EmployeeObj; import com.frank.rule.EmployeeDAO; public class SearchServlet extends HttpServlet { /** * Constructor of the object. */ public SearchServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String employeeName=request.getParameter("employeeName"); EmployeeDAO employeeDAO=new EmployeeDAO(); EmployeeObj employeeObj=employeeDAO.getEmployeeByName(employeeName); HttpSession session=request.getSession(); session.setAttribute("employee", employeeObj); response.sendRedirect("display.jsp"); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } } 此Servlet調用業務類的getEmployeeByName方法檢索人員基本信息,返回EmployeeObj對象,並放入session中,固然也能夠放入request中,根據本身的須要改進。頁面檢索成功後重定向到display.jsp進行信息的顯示(稍後講解) getEmployeeByName方法代碼以下: public EmployeeObj getEmployeeByName(String employeeName){ Connection conn=null; PreparedStatement pstmt=null; ResultSet rst=null; EmployeeObj employeeObj=new EmployeeObj(); try{ Class.forName("net.sourceforge.jtds.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa",""); String strSQL="SELECT employeeId,employeeName,age FROM EmployeeInfo WHERE employeeName=?"; pstmt=conn.prepareStatement(strSQL); pstmt.setString(1, employeeName); rst=pstmt.executeQuery(); if(rst.next()){ employeeObj.setEmployeeId(rst.getInt("employeeId")); employeeObj.setEmployeeName(rst.getString("employeeName")); employeeObj.setAge(rst.getInt("age")); return employeeObj; } return null; }catch(ClassNotFoundException ex){ ex.printStackTrace(); return null; }catch(SQLException ex){ ex.printStackTrace(); return null; }finally{ try{ pstmt.close(); conn.close(); }catch(Exception ex){ } } } display.jsp負責顯示查詢出的結果信息,代碼以下: < %@ page language="java" import="java.util.*,com.frank.obj.*" pageEncoding="ISO-8859-1"%> < % String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> < !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < html> < head> < base href="<%=basePath%>"> < title>My JSP 'display.jsp' starting page</title> < meta http-equiv="pragma" content="no-cache"> < meta http-equiv="cache-control" content="no-cache"> < meta http-equiv="expires" content="0"> < meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> < meta http-equiv="description" content="This is my page"> < !-- <link rel="stylesheet" type="text/css" href="styles.css"> --> < % EmployeeObj employeeObj=(EmployeeObj)session.getAttribute("employee"); %> < /head> < body> < table width="80" border="15"> < tr> < td width="30%" align="right">EmployeeId</td> < td width="70%" align="left"><%=employeeObj.getEmployeeId() %></td> < /tr> < tr> < td width="30%" align="right">EmployeeName</td> < td width="70%" align="left"><%=employeeObj.getEmployeeName() %></td> < /tr> < tr> < td width="30%" align="right">Age</td> < td width="70%" align="left"><%=employeeObj.getAge() %></td> < /tr> < tr> < td width="30%" align="right">Pic</td> < td width="70%" align="left"><img src="displayServlet?employeeId=<%=employeeObj.getEmployeeId() %>"/></td> < /tr> < /table> < /body> < /html> 代碼很是的簡單,只是簡單的從session中獲取保存的EmployeeObj對象,而後利用jsp表達式將數據成員信息顯示到頁面上。可是注意粗體部分,由於咱們須要將保存的圖片數據讀出,而後顯示成圖片。因此在此咱們利用Img元素顯示圖片,而Src利用displayServlet的運行結果輸出到客戶端,做爲圖片的顯示源。displayServlet包含參數employeeId,用來決定具體顯示哪一員工的圖片。 displayServlet經過Servlet輸出流,將讀取的圖片數據發送到客戶端,代碼以下: package com.frank.action; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.frank.rule.EmployeeDAO; public class DisplayServlet extends HttpServlet { /** * Constructor of the object. */ public DisplayServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/gif"); int employeeId=Integer.parseInt(request.getParameter("employeeId")); EmployeeDAO employeeDAO=new EmployeeDAO(); InputStream is=employeeDAO.getPicById(employeeId); int size=is.available(); byte[] image=new byte[size]; is.read(image); ServletOutputStream out=response.getOutputStream(); out.write(image); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } } 在此,調用業務類的getPicById方法獲得圖片數據的輸入流。而後獲取的輸入流寫到ServletOutputStream,這樣能夠在Servlet的輸出端使用,即img的src中使用 getPicById代碼以下: public InputStream getPicById(int employeeId){ Connection conn=null; PreparedStatement pstmt=null; ResultSet rst=null; InputStream is=null; try{ Class.forName("net.sourceforge.jtds.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa",""); String strSQL="SELECT pic FROM EmployeeInfo WHERE employeeId=?"; pstmt=conn.prepareStatement(strSQL); pstmt.setInt(1, employeeId); rst=pstmt.executeQuery(); if(rst.next()){ is=rst.getBinaryStream("pic"); return is; } return null; }catch(ClassNotFoundException ex){ ex.printStackTrace(); return null; }catch(SQLException ex){ ex.printStackTrace(); return null; }finally{ try{ pstmt.close(); conn.close(); }catch(Exception ex){ } } } 注意粗體部分 好了,咱們能夠經過運行結果來進行驗證,假設咱們搜索名稱爲Mike的人員數據,那麼這樣: 點search按鈕,運行結果以下: 好了,顯示出了檢索結果,不但包括人員的基本數據,保存到數據庫中的圖片數據也被讀出並顯示成圖片。 代碼只是利用jsp簡單的進行體現,你們能夠根據本身的須要進行改進 ---很抱歉截圖不能夠在這個上面顯示 ----
相關文章
相關標籤/搜索