今天为大家介绍一下如何用Servlet处理文件的上传,我们需要借助Apache Commons FileUpload包,同时需要Apache Commons IO包。
下面我们来编写处理文件上传的Servlet代码:
package com.gujin.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class Upload extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// 检查是否为一个上传文件的请求
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
{
// 创建磁盘为基础的文件项目的工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置工厂约束
factory.setSizeThreshold(10 * 1000);
// 配置存储库(以确保使用安全的临时位置)
ServletContext servletContext = this.getServletConfig()
.getServletContext();
File repository = (File) servletContext
.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
// 创建一个新的文件上传处理程序
ServletFileUpload upload = new ServletFileUpload(factory);
// 解析请求
try
{
List<FileItem> items = upload.parseRequest(request);
// 处理上传项
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext())
{
FileItem item = iter.next();
if (item.isFormField())
{
processFormField(item);
}
else
{
processUploadedFile(item);
}
}
}
catch (FileUploadException e)
{
e.printStackTrace();
}
}
response.sendRedirect("index.html");
}
private void processFormField(FileItem item)
{
String name = item.getFieldName();
String value = item.getString();
System.out.println("=====================================");
System.out.printf("%s:%s\n", name, value);
}
private void processUploadedFile(FileItem item)
{
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
System.out.println("=====================================");
System.out.printf("%s:%s\n", fieldName, fileName);
System.out.printf("%s:%s\n", "contentType", contentType);
System.out.printf("%s:%s\n", "isInMemory", isInMemory + "");
System.out.printf("%s:%s\n", "size", sizeInBytes + "");
}
}
同样的需要在web.xml
中进行配置
<servlet>
<description></description>
<display-name>Upload</display-name>
<servlet-name>Upload</servlet-name>
<servlet-class>com.gujin.servlet.Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
然后我们编写测试的Html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Servlet</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="upload">
File to upload: <input type="file" name="upfile"><br /> Notes
about the file: <input type="text" name="note"><br /> <br /> <input
type="submit" value="Press"> to upload the file!
</form>
</body>
</html>
我们可以测试一下,控制台会输出类似如下新信息:
=====================================
upfile:12.png
contentType:image/png
isInMemory:true
size:6558
=====================================
note:12