使用第三方组件实现上传文件功能需要在项目lib下目录导入两个Jar包(commons-fileupload 和 commons-io)
commons-io下载地址:http://commons.apache.org/proper/commons-io/download_io.cgi
commons-fileupload下载地址:http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi
关键步骤:
- 在JSP文件中使用page指令导入Commons-FileUpload组件所需的类
- 判断请求信息中的内容是否是multipart类型,如果是则进行处理
- 通过FileItemFactory工厂对象实例化ServletFileUpload对象
- 调用ServletFileUpload对象的parseRequest()将表单中字段解析成FileItem对象的集合
- 通过迭代依次处理每个FileItem对象,如果是普通字段,通过getString()方法得到相应表单字符的值,该值与表单字段中的"name"属性对应,如果是文件字段,则通过File的构造方法构建一个指定路径名和文件名的文件,并通过FileItem对象的Write()的方法将上传文件的内容保存到文件中
示例代码:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="doindex.jsp" enctype="multipart/form-data" method="post">
姓名:<input type="text" name="username">
<input type="file" name="filename">
<input type="submit" value="提交">
</form>
</body>
</html>
处理index.jsp请求的页面doindex.jsp
<%@page import="org.apache.commons.fileupload.FileUploadBase"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'doindex.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<%
request.setCharacterEncoding("utf-8");
String uploadFileName = "";//上传的文件名
String fieldName = "";//表单字段name的属性值
//请求信息中的内容是否是multipart类型
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//上传文件的储存路径(服务器文件系统上的绝对文件路径)
String uploadFilePath = request.getSession().getServletContext()
.getRealPath("/WEB-INF/upload/");
//判断请求的表单是否是multipart/form-data类型
if (isMultipart) {
//创建临时文件目录
File tempPathFile = new File("E:\\temp\\buffer\\");
if (!tempPathFile.exists()) //判断文件或者目录是否存在
tempPathFile.mkdirs(); //创建指定的目录,包括所有必需但不存在的目录
//创建解析Fileitem工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置缓存区大小(4k);
factory.setSizeThreshold(4*1024);
//设置上传文件用到的临时文件存放路径
factory.setRepository(tempPathFile);
//创建上传文件对象
ServletFileUpload upload = new ServletFileUpload(factory);
//设置整个文件允许大小
upload.setFileSizeMax(30*1024*1024);//30M
//设置完整请求的最大允许大小
upload.setSizeMax(60*1024*1024);//60M
try {
//解析请求
List<FileItem> items = upload.parseRequest(request);
//迭代
Iterator<FileItem> iter = items.iterator();
//逐个处理每一个表单
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
//普通表单字段
if (item.isFormField()) {
fieldName = item.getFieldName();
if (fieldName.equals("username")){
out.print(item.getString("utf-8") + "上传了文件!");
}
//文件表单字段
}else{
String fileName = item.getName();
List<String> fileType = Arrays.asList("gif", "bmp",
"jpg", "png");
String ext = fileName.substring(fileName
.lastIndexOf(".") + 1);
if (!fileType.contains(ext)) {
out.print("文件上传失败,文件类型只能是gif,bmp,jpg,png格式!");
}else{
if (fileName != null && !fileName.equals("")) {
//得到文件名
File fullFile = new File(item.getName());
//文件上传路径及文件名
File saveFile = new File(uploadFilePath,
fullFile.getName());
//上传文件
item.write(saveFile);
uploadFileName = fullFile.getName();
out.print("上传成功后的文件名是:" + uploadFileName+"文件大小是:"+item.getSize()/1024/1024+"M!");
}
}
}
}
//表单大小上传异常
}catch(FileUploadBase.SizeLimitExceededException ex){
out.print("表单完整大小为:"+upload.getSizeMax()/1024/1024+"M!");
//单个文件上传异常
}catch(FileUploadBase.FileSizeLimitExceededException ex){
out.print("上传文件过大:"+upload.getFileSizeMax()/1024/1024+"M!");
}catch(Exception e){
out.print("出错了!");
}
}
%>
<body>
</body>
</html>