【本文简介】
一个servlet 多文件上传的简单例子。
【依赖包】
- commons-fileupload-1.3.1.jar
- commons-io-2.2.jar
【依赖包下载】
- commons-fileupload-1.3.1.jar:http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi
- commons-io-2.2.jar:http://commons.apache.org/proper/commons-io/download_io.cgi
【文件夹结构】
【HTML表单】
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input name="file" type="file" />
<input type="submit" value="上传"/>
</form>
</body>
【java代码】
package com.zjm.www.servlet; import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator; 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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload; /**
* @描述 servlet 通过 FileItem 实现多文件上传
* @作者 小M
* @博客 http://www.cnblogs.com/xiaoMzjm/
* @时间 2014/07/30
*/
public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} @SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { // 转码,建议使用过滤器转码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8"); // 判断提交过来的表单是否为文件上传菜单,只适用于servlet
boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) {
// 构造一个文件上传处理对象
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory); Iterator<FileItem> items; try {
// 解析表单中提交的所有文件内容
items = upload.parseRequest(request).iterator(); while (items.hasNext()) { FileItem item = (FileItem) items.next(); if (!item.isFormField()) { // 取出上传文件的文件名称
String name = item.getName(); // 取得上传文件以后的存储路径
String fileName = name.substring(
name.lastIndexOf('\\') + 1, name.length()); // 上传文件以后的存储路径 , 有关路径问题,请参考另一篇博文:http://www.cnblogs.com/xiaoMzjm/p/3878758.html
String path = request.getServletContext().getRealPath("/")+"\\UpLoadFile"
+ File.separatorChar + fileName; // 上传文件
File uploaderFile = new File(path);
item.write(uploaderFile); // 打印上传成功信息
PrintWriter out = response.getWriter();
out.print("success");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}