这是使用了commons-fileupload-1.2.1.jar 和 commons-io-1.4.jar这两个组件来上传文件的!
package upload;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//1、先获取工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//2、获取上传处理对象(要把工厂对象传递给它)
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(32768);//允许最大32KB
//3、解析请求参数,过滤掉不是文件上传框的参数
List<?> itemList = null;
try {
itemList = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
for(int i = 0;i<itemList.size();i++){
FileItem fileItem = (FileItem)itemList.get(i);
System.out.println("文件名字为:"+fileItem.getName());
if(!fileItem.isFormField()){//判断是不是文件上传控件
//先获取客户端上传文件的File对象
System.out.println(fileItem.getName());
File sourceFile = new File(fileItem.getName());
System.out.println(sourceFile.getName());
//创建将要上传至服务器端的文件对象
File destFile = new File("D:\\temp", sourceFile.getName());
try {
fileItem.write(destFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
System.out.println("上传成功");
}
}