一般在用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 > |
到此已经完成一个简单的上传文件功能了——访问表单页面,选择文件后点击上传文件即可。如果想要在上传文件到服务器的同时,又要将文件保存到数据库中,可以在获取到文件名后,将文件名保存到数据库里,这样以后可以根据文件名把用户的文件选择出来!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。