Apache的Commons FileUpload是一个不错的附件上传组件,现把大体过程分享一下。
1.所需的jar包:
commons-fileupload-1.2.2.jar
commons-io-2.4.jar
2.配置一个上传的servlet
<servlet>
<description></description>
<display-name>FileUploadServlet</display-name>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>cn.hailiang.fileupload.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/FileUploadServlet</url-pattern>
</servlet-mapping>
3.FileUploadServlet的代码
package cn.hailiang.fileupload;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
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.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileUploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
// 判断请求是否包含 multipart数据
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
try {
String path = "c:\\attachment\\";// 设置附件保存路径
File attachementPath = new File(path);
if (!attachementPath.exists()) {
attachementPath.mkdir();
}
File tempPath = new File("c:\\AttachmentTemp\\");// 设置临时目录
if (!tempPath.exists()) {
tempPath.mkdir();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024 * 1);// 初始内存大小1M,超出后则直接保存到临时目录中
factory.setRepository(tempPath);// 设置临时目录
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// upload.setFileSizeMax(1024 * 1024 * 50);// 设置单个文件上传大小为50M
List<FileItem> items = upload.parseRequest(request);
System.out.println("items=" + items);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
// 处理HTML表单域
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("UTF-8");
System.out.println("FieldName=" + name + " \t FieldValue=" + value);
}
} else {
// 处理附件
String fieldName = item.getFieldName();
String _fileName = item.getName();
long _fileSize = item.getSize();
if (_fileSize == 0) {
continue;
}
System.out.println("附件大小为: " + (_fileSize / 1024) + " KB");
// 保存附件
_fileName = _fileName.substring(_fileName.lastIndexOf("\\") + 1);
File uploadedFile = new File(path + _fileName);
if (!uploadedFile.exists()) {
item.write(uploadedFile);
} else {
System.out.println("附件已经存在");
}
System.out.println("附件保存路径为:" + path + _fileName);
}
}
} catch (FileSizeLimitExceededException e) {
e.printStackTrace();
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
4.上传页面的代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>commons-fileupload 演示</title>
</head>
<body>
<form action="/FileUploadServlet" enctype="multipart/form-data" method="post">
标题 <input type="text" name="Title" value="文件上传测试"/><br><br>
备注 <input type="text" name="Remark" value="备注"><br><br>
附件1 <input type="file" name="attachment1"><br><br>
附件2 <input type="file" name="attachment2"><br><br>
<input type="submit" value=" 提交 ">
</form>
</body>
</html>
5.效果截图:
此组件配置和使用起来,都相对比较简单,只要参照官网的Uer guide,基本上都能搞定。
来源:oschina
链接:https://my.oschina.net/u/140680/blog/108129