標籤:
1.要實現圖片上傳,首先需要一個組件,這裡我用的是smartupload.jar可以到這裡下載http://download.csdn.net/detail/mengdecike/8279247
2.下載之後把這個檔案直接複製到WebContent/WEB-INF/lib下面
3.jsp頁面
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body>10 <form action="UpLoad" method="post" enctype="multipart/form-data" name="form1">11 <p>使用者名稱:12 <label for="username"></label>13 <input type="text" name="username" id="username">14 </p>15 <p>頭 像:16 <label for="photo"></label>17 <input type="file" name="photo" id="photo">18 </p>19 <p>20 <input type="submit" name="button" id="button" value=" 提 交 ">21 </p>22 </form>23 </body>24 </html>
4.上傳的servlet代碼如下:
1
request.setCharacterEncoding("utf-8");//設定字元 2 response.setContentType("text/html;charset=utf-8"); 3 response.setCharacterEncoding("utf-8"); 4 PrintWriter out =response.getWriter();//擷取out輸出對象 5 6 // 準備上傳目錄 7 String path = this.getServletContext().getRealPath("images"); 8 File fpath = new File(path); 9 if(!fpath.exists()){10 fpath.mkdir();11 }12 13 // 執行個體化組件14 SmartUpload su = new SmartUpload("utf-8");15 // 初始化組件16 su.initialize(this.getServletConfig(), request, response);17 18 try {19 // 限定20 su.setAllowedFilesList("jpg,png,gif");21 su.setMaxFileSize(50*1024); // 不能超過50K22 23 // 上傳並提取檔案24 su.upload();25 SmartFile file = su.getFiles().getFile(0);26 // 組建檔案名27 String fname = new Date().getTime()+"."+file.getFileExt();28 // 儲存檔案29 file.saveAs(path+"/"+fname);30 //file.saveAs(path+"/"+fname,1);31 // 提示32 out.println("<script>alert(‘檔案上傳成功!‘);location.href=‘upload.jsp‘;</script>");33 34 // 提取欄位資訊35 String username = su.getRequest().getParameter("username");36 System.out.println(">>> " + username);37 38 // 進行資料庫操作39 40 41 } catch(SecurityException e){42 out.println("<script>alert(‘只能上傳jpg、png、gif的檔案並且不能超過50K!‘);history.back();</script>");43 e.printStackTrace();44 }45 catch (SmartUploadException e) {46 // TODO Auto-generated catch block47 out.println("<script>alert(‘檔案上傳失敗!‘);history.back();</script>");48 e.printStackTrace();49 }50
如果需要整個的完整資源可以到http://download.csdn.net/detail/mengdecike/8279275 下載資源。
jsp圖片上傳