<span style="font-family: Arial, Helvetica, sans-serif;">代码中用到了2个jar包,分别是commons-io-2.1.jar和commons-fileupload-1.2.2.jar</span>
<pre name="code" class="java">可以去链接:http://pan.baidu.com/s/1eRAPLaq 密码:k1g1下载
package servlet;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
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;
/**
* 演示使用commons-fileupload组件上传文件
*/
public class UploadServlet2 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//创建一个基于硬盘的文件工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//内存只能放200M,多出来的放在临时目录下
factory.setSizeThreshold(200*1024*1024);
//临时目录
factory.setRepository(new File("F:\\temp"));
//解析 upload对象,需要传入factory
ServletFileUpload upload = new ServletFileUpload(factory);
//upload.setHeaderEncoding(req.getCharacterEncoding());//解决http报头乱码,即中文文件名乱码
try {
//解析请求对象,得到所有的表单域
List<FileItem> items = upload.parseRequest(req);
for(FileItem item:items){
if(item.isFormField()){
//获得普通表单的名字和值
System.out.println(item.getFieldName()+"------------->"+item.getString("utf-8"));//解决中文乱码问题
}else{
String saveDir = "upload";
//获得绝对路径(getServletContext().getResource("WEB-INF/web.xml"))获取配置文件
String realPath = req.getServletContext().getRealPath("/");
File saveDirFile = new File(realPath+"/"+saveDir);
if(!saveDirFile.exists()){
saveDirFile.mkdirs();
}
//生成文件名
String name = UUID.randomUUID().toString()+"."+item.getName().substring(item.getName().lastIndexOf("."));
//构建要保存的文件
File saveFile = new File(saveDirFile,name);
//保存到服务器
item.write(saveFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}