一般在用Servlet處理表單元素時,表單元素都是一些簡單的文本,Servlet很容易用Request.getParameter()就可以處理。但是當表單不止包含一些簡單的文本,比如有上傳文件域時,Servlet直接從HttpServletRequest對象中解析出復合表單的每一個子部分仍然是一項非常復雜的工作.
為了簡化對“multipart/form-data”類型數據的處理過程,可以采用相應的組件進行處理,這樣可以節省很大的編碼、支持重用,效率也挺高。
對于Java的組件也有一些:FileUpload、SmartUpload和Cos等等,本文就以Apache的FileUpload講解一下。
要使用FileUpload,首先應下載相應組件:
1.fileupload軟件包:http://commons.apache.org/fileupload/
2.io軟件包:http://commons.apache.org/io/
下載后解壓zip 包,將commons-fileupload-1.2.1.jar和commons-io-1.4.jar 復制到tomcat 的webapp/WEB-INF/lib下。
一、表單頁面(要指定表單的enctype="multipart/form-data")——Upload.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
< html > < head > < title >Upload</ title > </ head > < body > < form name = "uploadForm" method = "POST" enctype = "MULTIPART/FORM-DATA" action = "upload" > < table > < tr > < td >< div align = "right" >User Name:</ div ></ td > < td >< input type = "text" name = "username" size = "30" /> </ td > </ tr > < tr > < td >< div align = "right" >Upload File1:</ div ></ td > < td >< input type = "file" name = "file1" size = "30" /> </ td > </ tr > < tr > < td >< div align = "right" >Upload File2:</ div ></ td > < td >< input type = "file" name = "file2" size = "30" /> </ td > </ tr > < tr > < td >< input type = "submit" name = "submit" value = "upload" ></ td > < td >< input type = "reset" name = "reset" value = "reset" ></ td > </ tr > </ table > </ form > </ body > </ html > |
二、處理表單的Servlet——UploadServlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
package mypack; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import org.apache.commons.fileupload.*; import org.apache.commons.fileupload.servlet.*; import org.apache.commons.fileupload.disk.*; public class UploadServlet extends HttpServlet { private String filePath; //存放上傳文件的目錄 private String tempFilePath; //存放臨時文件的目錄 public void init(ServletConfig config) throws ServletException { super .init(config); filePath=config.getInitParameter( "filePath" ); tempFilePath=config.getInitParameter( "tempFilePath" ); filePath=getServletContext().getRealPath(filePath); tempFilePath=getServletContext().getRealPath(tempFilePath); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/plain" ); //向客戶端發送響應正文 PrintWriter outNet=response.getWriter(); try { //創建一個基于硬盤的FileItem工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //設置向硬盤寫數據時所用的緩沖區的大小,此處為4K factory.setSizeThreshold( 4 * 1024 ); //設置臨時目錄 factory.setRepository( new File(tempFilePath)); //創建一個文件上傳處理器 ServletFileUpload upload = new ServletFileUpload(factory); //設置允許上傳的文件的最大尺寸,此處為4M upload.setSizeMax( 4 * 1024 * 1024 ); List /* FileItem */ items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { processFormField(item,outNet); //處理普通的表單域 } else { processUploadedFile(item,outNet); //處理上傳文件 } } outNet.close(); } catch (Exception e){ throw new ServletException(e); } } private void processFormField(FileItem item,PrintWriter outNet){ String name = item.getFieldName(); String value = item.getString(); outNet.println(name+ ":" +value+ "/r/n" ); } private void processUploadedFile(FileItem item,PrintWriter outNet) throws Exception{ String filename=item.getName(); int index=filename.lastIndexOf( "//" ); filename=filename.substring(index+ 1 ,filename.length()); long fileSize=item.getSize(); if (filename.equals( "" ) && fileSize== 0 ) return ; File uploadedFile = new File(filePath+ "/" +filename); item.write(uploadedFile); outNet.println(filename+ " is saved." ); outNet.println( "The size of " +filename+ " is " +fileSize+ "/r/n" ); } } |
該Servlet在Web.xml中其配置為:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
< servlet > < servlet-name >upload</ servlet-name > < servlet-class >mypack.UploadServlet</ servlet-class > < init-param > < param-name >filePath</ param-name > < param-value >store</ param-value > </ init-param > < init-param > < param-name >tempFilePath</ param-name > < param-value >temp</ param-value > </ init-param > </ servlet > < servlet-mapping > < servlet-name >upload</ servlet-name > < url-pattern >/upload</ url-pattern > </ servlet-mapping > |
到此已經完成一個簡單的上傳文件功能了——訪問表單頁面,選擇文件后點擊上傳文件即可。如果想要在上傳文件到服務器的同時,又要將文件保存到數據庫中,可以在獲取到文件名后,將文件名保存到數據庫里,這樣以后可以根據文件名把用戶的文件選擇出來!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。