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); // 不能超過50K 22 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 block 47 out.println("<script>alert('文件上傳失敗!');history.back();</script>"); 48 e.printStackTrace(); 49 } 50
如果需要整個的完整資源可以到http://download.csdn.net/detail/mengdecike/8279275 下載資源。