1。需要两个夹包文件:

commons-fileupload-1.2.1.jar、

commons-io-1.4.jar


2。页面文件上传



<form action="upload" method="post" enctype="multipart/form-data">
file:<input type="file" name="file" /><br/>
username:<input type="text" name="username"/><br/>
<input type="submit" value="submit"/>
</form>
</body>


3.servlet处理页面请求;



package org.yinhe.servlet;

import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class UpLoadServlet extends HttpServlet {


@SuppressWarnings("unchecked")
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
FileItem item = null;
List<FileItem> items = upload.parseRequest(request);
for (int i = 0; i < items.size(); i++) {
item = items.get(i);
if(item.isFormField()){
//如果是普通的控件
String fileName = item.getFieldName();
String username = item.getString();
System.out.println(fileName + ":" + username);
}else{
//如果是文件上传的控件,一般我们需要将
//其内容转化为一个文件,并保存到服务器上面。
//item.getName()返回的文件名:某些操作系统
//,返回的文件名包含了路径,有一些不包含。
String name = item.getName();
String name2 = name.substring(name.lastIndexOf("/")+1);
System.out.println("name:"+name2);
//获取保存文件的路径
//getRealPath:返回服务器的某个目录的绝对路径。
String path = this.getServletContext().getRealPath("upload");
System.out.println("path:" + path);
item.write(new File(path+"/" + name2));
}
}
} catch (Exception e) {
throw new ServletException(e.getMessage());
}
response.sendRedirect("sucess.jsp");
}

}