common-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/下载。
该组件简单易用,可实现一次上传一个或多个文件,并可限制文件大小。
下载后解压zip包,将commons-fileupload.jar,和commons-io里面后缀为jar复制到你的项目的webapp\WEB-INF\lib\下,如果目录不存在请自建目录。
这个项目是用来上传文件,文件路径为workspace\项目名称\build\weboutput\file\项目下,如果没有该文件夹请创建一个。否则会发生找不到路径的情况
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 implementation class FileUpload
*/
public class FileUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FileUpload() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//判断提交过来的表单是否为文件上传菜单
boolean isMultipart= ServletFileUpload.isMultipartContent(request);
if(isMultipart){
//构造一个文件上传处理对象
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator 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());
//上传文件以后的存储路径
String path= request.getRealPath("file")+File.separatorChar+fileName;
//上传文件
File uploaderFile = new File(path);
item.write(uploaderFile);
//打印上传成功信息
response.setContentType("text/html");
response.setCharacterEncoding("GB2312");
PrintWriter out = response.getWriter();
out.print("<font size='2'>上传文件为:"+name+"<br>保存的地址为"+path+ "</font>");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}