平常项目中需要用到文件的上传,下面将详细介绍在Servlet中使用commons-fileupload-1.3.jar进行文件上传的经过。首先项目中要导入JAR包commons-fileupload-1.3.jar、commons-io-2.3.jar。但这也有缺点,不能上传大文件。
1、编写Servlet类
package com.fileupload;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UpLoadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory df = new DiskFileItemFactory();
//设定阀值1M,如果超过这个值,则文件就直接写到临时文件,不会一直占用内存
//利用这个特性可在上传大文件的时候不会占用大量内存,可以提高并发使用量。
df.setSizeThreshold(1024 * 1024);
try {
File f = new File("E:\\preprocess_gd_package\\temp");
if (!f.exists()) {
f.mkdirs();
}
df.setRepository(f);
ServletFileUpload sf = new ServletFileUpload(df);
sf.setFileSizeMax(1024 * 1024 * 100);//上传文件最大为100M
List list = sf.parseRequest(request);
for (int i = 0; i < list.size(); i++) {
FileItem fileItem = (FileItem) list.get(i);
String fileName = fileItem.getName();
if(fileName == null || "".equals(fileName.trim())){
continue;
}
File ff = new File("E:\\preprocess_gd_package\\files");
if (!ff.exists()) {
ff.mkdirs();
}
File f2 = new File(ff, fileName);
fileItem.write(f2);
}
} catch (Exception e) {
e.printStackTrace();
}
response.setContentType("text/html");
response.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
out.println("<script>alert('文件上传成功!');</script>");
out.flush();
out.close();
}
}
2、配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>com.fileupload.UpLoadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
</web-app>
3、编写index.jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
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>文件上传</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">
</head>
<body>
<form action="fileupload" method="post" enctype="multipart/form-data" name="form1">
<input type="file" name="file">
<input type="submit" name="Submit" value="upload">
</form>
</body>
</html>
4、运行结果