- 环境准备
–
在项目中引入
commons-fileupload-1.2.2.jar
和
commons-io-2.4.jar
文件
- 设置表单的enctype属性
<form action="UploadServlet" method="post" enctype="multipart/form-data">
注意:
上传文件时
form
标签的
method
属性必须取值为“
post”
,不能取值为“
get”
- 编写上传文件处理页的实现步骤
//创建FileItemFactory对象 //创建ServletFileUpload对象 //解析form表单中所有文件 if (普通表单字段){ //获取表单字段的name属性值 if (此属性是“user”)){ //输出XXX上传了文件 } }else{ //文件表单字段 //获取上传文件的名字 if (名字不为空) { //保存此文件并输出保存成功 } }
- 实例
1. index.jsp
<body>
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
用户名 <input type="text" name="username" /> <br> 上传文件<input
type="file" name="file" /> <br> <input type="submit" value="提交" />
</form>
</body>
2. UploadServlet
package com.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory factory = new DiskFileItemFactory();
//使用工厂对象实例化上传组件ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//使用集合获取表单的所有数据
List<FileItem> items = upload.parseRequest(request);
for (int i =0;i<items.size();i++){
FileItem item = items.get(i);
//普通表单域
if(item.isFormField()){
//获得表单元素的name
String name = item.getFieldName();
if(name.equals("username")){
//获得表单元素的值
String value =item.getString("utf-8");
System.out.println("name:"+name+"\tvalue:"+value);
}
}else{
//上传文件
//获得文件在Apache的保存路径
String filepath = getServletContext().getRealPath("/");//根目录
String filename = item.getName();//文件名称,上传文件的真实名称
String path = filepath +"upload\\"+filename;
//创建一个文件对象
File file = new File(path);
//生成一个文件(复制)
item.write(file);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print("文件上传成功");
out.flush();
out.close();
}
}
- 测试