Java使用Apache的FileUpload组件进行文件上传
首先需要导入jar包
commons-fileupload-1.3.2.jar
commons-io-2.5.ajr
Html代码
<fieldset>
<legend>FileUpload文件上传</legend>
<form method="post" enctype="multipart/form-data" action="NormalUpload">
<label>用户名:<input type="text" name="username" /></label><br />
<label>文 件:<input type="file" name="file01" /></label><br />
<input type="submit" />
</form>
</fieldset>
Servlet代码
public class NormalUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.创建工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
// 2.创建文件上传核心类
ServletFileUpload upload = new ServletFileUpload(factory);
// 【设置单文件最大值:5M】
upload.setFileSizeMax(5 * 1024 * 1024);
// 【设置总文件最大值: 20M】
upload.setSizeMax(20 * 1024 * 1024);
// 设置编码
upload.setHeaderEncoding("utf-8");
// 3.判断是否为文件上传表单
if (ServletFileUpload.isMultipartContent(request)) {
try {
// 4.遍历表单项
@SuppressWarnings("unchecked")
List<FileItem> list = upload.parseRequest(request);
for (FileItem item : list) {
// 普通表单项
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("UTF-8");
System.out.println(name + " : " + value);
} else {// 文件表单项
// 文件名
String fileName = item.getName();
// 生成唯一文件名
fileName = UUID.randomUUID().toString() + "#" + fileName;
// 获取上传路径:项目目录下的upload文件夹(先创建upload文件夹)
String basePath = this.getServletContext().getRealPath("/upload");
// 创建文件对象
File file = new File(basePath, fileName);
// 写文件(保存)
item.write(file);
// 删除临时文件
item.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} else {
response.getWriter().write("cannot deal this request!");
}
}
}