1.导入jar包
common-fileupload.jar
common-io.jar
2.jsp页面(样式省略)
<body>
<form action="UploadServlet" enctype="multipart/form-data" method="post">
用户名:<input type="text" name="username" /><br>
上传文件:<input type="file" name="fileName" /><br>
<input type="submit" value="文件上传" /><br>
</form>
</body>
3.创建名为UploadServlet的Servlet,并在doPost()方法中编写实现代码,如下所示:
package com.upload.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
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.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
/**
* Servlet implementation class UploadServlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UploadServlet() {
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
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");// 设置响应编码
// 得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
String savePath = request.getServletContext().getRealPath("/WEB-INF/upload");
// 上传时生成的临时文件保存目录
String tempPath = request.getServletContext().getRealPath("/WEB-INF/temp");
File tmpFile = new File(tempPath);
if (!tmpFile.exists()) {
// 创建临时目录
tmpFile.mkdir();
}
// System.out.println("文件临时保存路径1:"+tempPath);
// 1.创建磁盘工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 100);// 设置缓冲区的大小为100KB,如果不指定,那么缓冲区的大小默认是10KB
factory.setRepository(new File(tempPath));// 设置上传时文件的保存目录
// 2.创建文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置允许上传文件的内存,这里设置为100KB,根据实际情况设置
upload.setSizeMax(1024 * 100);
// 3.判断提交上来的数据是否是上传表单的数据
if (ServletFileUpload.isMultipartContent(request)) {
try {
// 4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
List<FileItem> list = upload.parseRequest(request);
// 设置解析到的文件编码格式
upload.setHeaderEncoding("utf-8");
for (FileItem fileItem : list) {
// 判断是否文件,结果为“true”就是普通表单,如果为“false”则是文件
if (fileItem.isFormField()) {
String fileName = fileItem.getFieldName();// 获得表单name属性名
System.out.println(fileItem.getString("utf-8"));// 获取表单value值,并设定编码方式
} else {
String name = fileItem.getName();// 获取上传文件的名字
// 限制上传文件的类型
List<String> fileType = Arrays.asList("gif", "bmp", "jpg", "png");//允许上传文件的类型
String fileExtName = name.substring(name.lastIndexOf(".") + 1);//获得文件的后缀名
//System.out.println("上传文件的后缀名为:"+fileExtName);
if (!fileType.contains(fileExtName)) {
System.out.println("上传失败!文件类型只能是gif、bmp、jpg、png!");
} else {
InputStream input = fileItem.getInputStream();// 获得上传文件字节流
// 创建输出文件
String outPath = request.getServletContext().getRealPath(name);
FileOutputStream output = new FileOutputStream(new File(outPath));
// 使用IOUtils工具输出,也就是copy文件
IOUtils.copy(input, output);
System.out.println("上传成功!");
System.out.println("保存的路径为:" + outPath);
// 关闭输入流
input.close();
// 关闭输出流
output.close();
// 删除处理文件上传时生成的临时文件
fileItem.delete();
}
}
}
} catch (FileUploadBase.SizeLimitExceededException e) {
System.out.println("上传失败!上传的文件大小超出限制,最大只能上传"+upload.getSizeMax()+"bytes的文件");
} catch (Exception e) {
System.out.println("上传失败!");
e.printStackTrace();
}
} else {
// 如果不是文件上传类型,则采用普通表单获取方式
request.setCharacterEncoding("UTF-8");
String parameter = request.getParameter("username");
System.out.println(parameter);
}
}
}