Java Web實踐專題——圖片管理

來源:互聯網
上載者:User
 

在一個網站中可能會存在大量的圖片,有些圖片對於所有的網頁是相同的,例如網頁的LOGO,首頁中的圖片,這些圖片就像普通的html檔案一樣,這些圖片的處理通常使用網頁編輯工具來完成的,也就是說通常是由美工完成的。主要使用下面的html標籤:<img alt="" src=""/>其中src指定檔案的路徑,使用相對路徑,通常我們會在web應用中專門建立一個檔案夾images存放所有的圖片。這些圖片的處理一般不需要Java程式員管理。還有一些圖片是與程式員需要考慮的,例如,網站有一個留言板,在留言的時候使用者可以選擇表情,表情是一個非常簡單的圖片,每個使用者留言都會選擇一個,如果不選擇,系統也會給一個預設的。這裡使用圖片的特點是、大家共用這麼多的圖片,不管怎麼選擇,都是從中選擇。對於這種圖片的處理通常的做法:在記錄留言的同時,記錄圖片的編號,這樣在顯示的時候根據圖片的編號尋找圖片本身。另外還有一種情況,如果系統要儲存所有使用者的照片,這些照片對於不同的使用者是不相同的,這時候如果採用上面的方式圖片從完成的功能來說也可以,但是管理起來不方便,更合理的方式應該使用資料庫。通常通過上傳的方式把圖片上傳到伺服器,然後儲存到資料庫,然後需要的時候,從資料庫提取然後顯示。下面分別對兩種處理圖片的方式進行介紹。 通過路徑管理圖片這種方式下,為了訪問檔案方便,需要對檔案名稱進行特殊設定,例如上面所說的20種表情圖片,可以使用image01.gif、image02.gif、image03.gif等等。(1)       路徑的產生首先在html檔案中選項按鈕讓使用者選擇,例如下面的代碼展示了20種被選擇的表情,使用上面說的檔案名稱命名方式。請選擇表情:<br><input type="radio" name="mode" value="01"/><img alt="表情1" src="images/image01.gif" /><input type="radio" name="mode" value="02"/><img alt="表情2" src="images/image02.gif" /><input type="radio" name="mode" value="03"/><img alt="表情3" src="images/image03.gif" />…這裡需要注意的mode是選項按鈕的名字,處理檔案中會根據這個名字擷取使用者選擇的資訊,value對應的某個選項的值,如果你選擇第一個圖片,則選項按鈕的值就是01。img標籤用於顯示表情圖片。然後在處理檔案中擷取這個參數,把它儲存到資料庫中,擷取資訊,可以通過下面的程式碼完成:request.getParameter(“mode”);如何向資料庫中儲存,請參考本書中關於資料庫部分。(2)       根據路徑資訊產生圖片首先,需要從資料庫中擷取到要顯示的圖片的路徑資訊,訪問資料庫的過程請參考本書中關於資料庫部分。假設擷取的資訊儲存在str中,通常我們會先儲存到request中,通過下面的代碼:request.setAttribute(“mode”,str);然後在頁面中顯示,需要根據這個路徑確定檔案名稱,所以img標籤中的檔案名稱部分需要根據這個變數確定。原來的格式為:<img src="images/image01.gif" />需要把01替換成變數,使用運算式:<img src="images/image${requestScope.mode}.gif" alt=""/>使用下面的代碼也可以得到相同的效果:<%            String str = (String)request.getAttribute("mode");            out.println("<img src=/"images/image"+str+".gif/" alt=/"/"/>");%>或者<%           String str2 = (String)request.getAttribute("mode");%><img src="images/image<%=str2%>.gif" alt=""/>使用儲存路徑的方式的思路非常簡單,儲存圖片的資訊到資料庫中,不一定是全部資訊,只要能確定圖片即可,然後根據資料庫中的資訊構造圖片的路徑顯示路徑。 通過資料庫儲存圖片在資料庫中儲存圖片,需要使用BLOB類型的欄位,BLOB用於儲存位元組流對象。假設我們要系統管理使用者資訊,為了簡化,這裡使用者資訊包括使用者名稱、使用者編號和照片,表的定義語句如下:create table user(userid varchar(10) primary key,username varchar(10),picture blob)下面分別對圖片的上傳、儲存和顯示進行介紹。(1)圖片的上傳檔案的上傳功能我們使用Struts中提供的上傳功能。首先需要建立上傳的介面,對應的代碼如下:<%@ page contentType="text/html; charset=GBK" %><%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %><html><head><title>adduser</title></head><body bgcolor="#ffffff"><h1>JBuilder Generated JSP</h1>使用者添加<br><html:form action="addAction.do" method="post" enctype="multipart/form-data">使用者編號:<html:text property="userid"/><br>使用者名稱:<html:text property="username"/><br>照片:<html:file property="picture"/><html:submit></html:submit></html:form></body></html>注意:請求方式是post,enctype的值為“multipart/form-data”。需要建立一個Form用於傳值:package picturetest; import org.apache.struts.action.ActionForm;import org.apache.struts.upload.FormFile;import org.apache.struts.action.ActionErrors;import org.apache.struts.action.ActionMapping;import javax.servlet.http.HttpServletRequest; public class AddActionForm    extends ActionForm { private FormFile picture; private String userid; private String username; public FormFile getPicture() {    return picture; }  public void setPicture(FormFile picture) {    this.picture = picture; }  public void setUsername(String username) {    this.username = username; }   public void setUserid(String userid) {    this.userid = userid; }  public String getUserid() {    return userid; }  public String getUsername() {    return username; }  public ActionErrors validate(ActionMapping actionMapping,                               HttpServletRequest httpServletRequest) {      /** @todo: finish this method, this is just the skeleton.*/    return null; }  public void reset(ActionMapping actionMapping,                    HttpServletRequest servletRequest) { }}(2)圖片的儲存圖片的儲存應該建立單獨的類來完成,因為代碼太多,這裡簡化,直接在Action中完成對資訊的添加。package picturetest; import org.apache.struts.action.ActionMapping;import org.apache.struts.action.ActionForm;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.ActionForward;import org.apache.struts.action.Action;import org.apache.struts.upload.FormFile; import java.sql.*;import java.io.*; public class AddAction    extends Action {  public ActionForward execute(ActionMapping mapping, ActionForm form,                               HttpServletRequest request,                               HttpServletResponse response) {     AddActionForm addActionForm = (AddActionForm) form;    String uid = addActionForm.getUserid();    String username = addActionForm.getUsername();    FormFile file = addActionForm.getPicture();    System.out.println(file.getFileSize());    if(file == null)      return mapping.findForward("success");    try    {      Class.forName("com.mysql.jdbc.Driver");      //載入驅動程式      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/webtest","root","");      //建立串連      PreparedStatement pstmt = con.prepareStatement("insert into user values(?,?,?)");      //建立語句對象      InputStream is = file.getInputStream();      //根據檔案建立輸入資料流      pstmt.setString(1,uid);      //為sql語句中的第一個變數賦值      pstmt.setString(2,username);      //為sql語句中的第二個變數賦值      pstmt.setBinaryStream(3,is,file.getFileSize());      //為sql語句中的第三個變數賦值,就是檔案輸入資料流      pstmt.execute();      //執行sql語句      is.close();      //關閉輸入資料流      pstmt.close();      //關閉語句對象      con.close();      //關閉連線物件    }catch(Exception e)    {      System.out.print(e.toString());    }    request.setAttribute("userid",uid);    request.setAttribute("username",username);    return mapping.findForward("success"); }}把圖片存入資料庫的過程主要是先根據檔案建立輸入資料流,然後把該輸入資料流作為參數添加到資料庫中。儲存圖片使用:pstmt.setBinaryStream(3,is,file.getFileSize());    其中,第一個參數3表示為sql語句中的第三個變數賦值,也就是第3個問號指定的變數,第二個參數is表示輸入資料流,第三個參數表示圖片的大小。如果這裡的圖片不是上傳的,而是位於檔案系統中,操作過程也非常類似:      String str = getServletContext().getRealPath("code.gif");      File file = new File(str);      InputStream fis = new FileInputStream(file);主要建立一個從圖片的輸入資料流即可,前面的是從上傳檔案的輸入資料流,這裡是從磁碟檔案的輸入資料流,後面我們還會介紹從記憶體配置圖片的輸入資料流。接下來向資料庫中儲存的過程是相同的。(3)圖片的顯示圖片本身的顯示通常伴隨有其它資訊的顯示,這裡把這個使用者的所有資訊都顯示出來,但是文本類資訊與圖片資訊本身的顯示過程不同,所以這裡使用兩個檔案:第一個檔案用於顯示圖片本身,第二個檔案用於顯示其它資訊以及關聯到圖片上。顯示圖片的檔案:<%@page contentType="image/jpeg"%><%@page import="java.sql.*"%><%@page import="java.io.*"%> <%    String driver = "com.mysql.jdbc.Driver";    String url = "jdbc:mysql://127.0.0.1:3306/webtest";    try {      String userid = request.getParameter("userid");      //擷取要顯示的使用者的ID      Class.forName(driver);      //載入驅動程式      Connection con = DriverManager.getConnection(url, "root", "");      //建立串連      String sql = "select picture from user where uid='"+userid+"'";      //String sql = "select picture from user where uid='00006789'";      PreparedStatement pstmt = con.prepareStatement(sql);      //建立語句對象      ResultSet rs = pstmt.executeQuery();      //查詢的結果集      rs.next();      InputStream is = rs.getBinaryStream(1);      //從資料庫中讀取圖片資料       byte b[] = new byte[8192];      //建立位元組數組,用於接收資料      OutputStream os = response.getOutputStream();      //擷取輸出資料流      int i;      while ((i=is.read(b)) > 0) { //從輸入資料流讀取資料        os.write(b); //然後把讀取的資料進行輸出      }      os.close();      is.close();      rs.close();      pstmt.close();      con.close();      //關閉相關對象    }    catch (Exception e) {      out.println(e.toString());    } %>需要注意幾個地方:Ø         page屬性的contentType屬性的值為:image/jpeg;Ø         讀取圖片,使用rs.getBinaryStream(1);Ø         需要擷取輸出資料流:OutputStream os = response.getOutputStream();Ø         把需要顯示的照片的使用者ID傳遞過來。顯示所有資訊的檔案:<%@ page contentType="text/html; charset=GBK" %><html><head><title>userinformation</title></head><body bgcolor="#ffffff"><h1>使用者資訊:</h1>使用者編號:${requestScope.userid}<br>使用者名稱:${requestScope.username}<br>照片:<img alt="照片" src="picture.jsp?userid=${requestScope.userid}" /></body></html>注意:照片:<img alt="照片" src="picture.jsp?userid=${requestScope.userid}" />,picture.jsp的作用就是產生圖片,src的值為picture.jsp就是把picture.jsp產生的圖片作為一個靜態圖片使用了,使用“?”號把要顯示的使用者ID傳遞給picture.jsp檔案。這裡不再給出設定檔struts-configure.xml的內容。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.