使用Servlet3.0上传文件

来源:互联网 发布:炫踪网络李化亮 编辑:程序博客网 时间:2024/05/16 10:17

Servlet3.0支持HttpServletRequest对文件的上传,提供了两个方法:

1.Part getPart(String name):根据名称获取文件的上传域。

2.Collection<Part> getParts():获取所有的文件上传域。


同时,需要指定form表单中的enctype属性。


enctype属性:http://www.zgguan.com/doc/w3c/tags/att_form_enctype.asp.htm


语法

<form enctype="value">

属性值

值描述application/x-www-form-urlencoded在发送前编码所有字符(默认)multipart/form-data

不对字符编码。

在使用包含文件上传控件的表单时,必须使用该值。

text/plain空格转换为 "+" 加号,但不对特殊字符编码。

可以看到,如果想要上传包含文件的控件时,enctype的值必须为:mulitipart/form-data。


上传文件后,在Servlet中使用request.getPart("name")就可以得到包含该文件的信息,然后可以使用part.write保存到本地磁盘。


举个例子:

新建一个form表单用来提交文件:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body><form action="upload" method="post" enctype="multipart/form-data">选择文件:<input type="file" name="file"><input type="submit" value="提交"></form></body></html>


然后使用Servlet处理该文件:


package test;import java.io.IOException;import java.io.PrintWriter;import java.util.Collection;import javax.servlet.ServletException;import javax.servlet.annotation.MultipartConfig;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.Part;@WebServlet("/upload")@MultipartConfig(location="F:\\file\\")public class upload extends HttpServlet {@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();request.setCharacterEncoding("UTF-8");Part part = request.getPart("file");out.print("文件类型为:" + part.getContentType() + "<br/>");out.print("文件的大小为:" + part.getSize() + "<br/>");out.print("文件信息为:" + part.getHeader("content-disposition") + "<br/>");out.print("文件的名字为:" + part.getSubmittedFileName());part.write(part.getSubmittedFileName());}}

在Servlet中使用request.getPart("file")就可以得到所上传文件的文件域(file是表单中指定的name值),然后可以根据Part对象的方法得到相应的内容。


而且,想要处理文件上传,该Servlet必须进行配置:


可以使用注解中的:@MultipartConfig进行配置。


也可以在web.xml中的servlet标签中添加:multipart-config进行配置。


这两种方法都支持四个属性:


  • location: An absolute path to a directory on the file system. The location attribute does not support a path relative to the application context. This location is used to store files temporarily while the parts are processed or when the size of the file exceeds the specified fileSizeThreshold setting. The default location is "".

  • fileSizeThreshold: The file size in bytes after which the file will be temporarily stored on disk. The default size is 0 bytes.

  • MaxFileSize: The maximum size allowed for uploaded files, in bytes. If the size of any uploaded file is greater than this size, the web container will throw an exception (IllegalStateException). The default size is unlimited.

  • maxRequestSize: The maximum size allowed for a multipart/form-data request, in bytes. The web container will throw an exception if the overall size of all uploaded files exceeds this threshold. The default size is unlimited.

使用方法:

For, example, the @MultipartConfig annotation could be constructed as follows:

@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024,     maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)

Instead of using the @MultipartConfig annotation to hard-code these attributes in your file upload servlet, you could add the following as a child element of the servlet configuration element in the web.xml file.

<multipart-config>    <location>/tmp</location>    <max-file-size>20848820</max-file-size>    <max-request-size>418018841</max-request-size>    <file-size-threshold>1048576</file-size-threshold></multipart-config>



来源于:http://docs.oracle.com/javaee/6/tutorial/doc/gmhal.html


可以看到在上述的例子中,就是用了注解@MultipartConfig(location="F\\file\\"),指定了文件保存的路径为F盘中的file文件夹。可以直接在servlet代码中使用part.write("文件名")就可以将该文件保存到:F盘中file文件夹下。(如果不适用location指定目录的话,需要使用part.write("F\\file\\文件名"))。


如果有多个文件的话,使用request.getParts(),就可以得到一个Collection<Part>对象,然后进行遍历就好了。


测试:
选择一个文件,这里是java的一个API文档。



然后点击提交,跳转到upload(也就是上述中使用注解配置的Servlet)进行处理,得到该文件的信息:



查看F盘下的file文件夹,可以看到已经得到了该文件:


0 0
原创粉丝点击