原理是前台post方式提交字节流,后台Request对象提供了一个getInputStream()方法获取,然后在指定的位置通过FileOutputStream生成文件。
通过js前台可以自动添加多文件上传,后台通过fileItem区分。
一般实现大文件上传的话肯定是不能使用HTTP协议的,因为这样会给服务器带来巨大的压力。使用HTTP协议上传一个500MB大小的文件,意味着要占用WEB服务器500MB的内存,如果同时有许多人上传这么大的文件,WEB服务器的内存会被撑爆。FTP的方式比HTTP的方式要更适合大文件的传输,而且借助于FTP协议可以轻松实现文件的断点续传。
- upload.jsp: A JSP page that displays an upload form.
- UploadServlet.java: A Java servlet that handles file upload.
- message.jsp: A JSP page that displays message to user after the file is uploaded.
- web.xml: defines and configures URL mapping for the servlet.
环境 Servlet2.5+ jre 1.5+
包 commons-fileupload-1.3.jar commons-io-2.2.jar
1:upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Demo</title>
</head>
<body>
<center>
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Demo</title>
</head>
<body>
<center>
//注意,一定要用字节流,因为,上传的文件可能是二进制文件,如图象文件,因此,使用字节流会更通用
<form method="post" action="uploadFile" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="uploadFile" />
<br/><br/>
<input type="submit" value="Upload" />
</form>
</center>
</body>
</html>
<form method="post" action="uploadFile" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="uploadFile" />
<br/><br/>
<input type="submit" value="Upload" />
</form>
</center>
</body>
</html>
2:FileUploadServlet.java
package com.mdcl.bgctv.fileManage.action;
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 FileUploadServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY="upload";
private static final int MEMORY_THRESHOLD = 1024*1024*3;
private static final int MAX_FILE_SIZE = 1024*1024*40;
private static final int MAX_REQUEST_SIZE = 1024*1024*50;
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
//表单是否符合文件上传规则
//判断客户端请求是否为POST,并且enctype属性是否是“multipart/form-data"
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer = response.getWriter();
writer.println("Error: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
//文件工厂类 判定初始文件内存以及文件超过内存时临时存放的位置
DiskFileItemFactory factory = new DiskFileItemFactory();
//以byte为单位设定文件使用多少内存量后,将文件存入临时存储
factory.setSizeThreshold(MEMORY_THRESHOLD);
//设定临时文件的存储路径
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//ServletFileUpload 处理同意HTML文件中多文件上传的类,继承自FileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
//设置允许上传文件的最大大小
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = getServletContext().getRealPath("")+File.separator +UPLOAD_DIRECTORY;
//根据存储路径生成文件夹
File uploadDir = new File(uploadPath);
if(!uploadDir.exists()){
uploadDir.mkdir();
}
try{
List<FileItem> formItems = upload.parseRequest(request);
if(formItems!=null && formItems.size()>0){
for(FileItem item:formItems){
if(!item.isFormField()){
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
System.out.println("filePath" + filePath);
File storeFile = new File(filePath);
//写入文件
item.write(storeFile);
request.setAttribute("message", "Upload has been done successfully!");
}
}
}
}catch (Exception ex){
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}
}
3:message.jsp
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 FileUploadServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY="upload";
private static final int MEMORY_THRESHOLD = 1024*1024*3;
private static final int MAX_FILE_SIZE = 1024*1024*40;
private static final int MAX_REQUEST_SIZE = 1024*1024*50;
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
//表单是否符合文件上传规则
//判断客户端请求是否为POST,并且enctype属性是否是“multipart/form-data"
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer = response.getWriter();
writer.println("Error: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
//文件工厂类 判定初始文件内存以及文件超过内存时临时存放的位置
DiskFileItemFactory factory = new DiskFileItemFactory();
//以byte为单位设定文件使用多少内存量后,将文件存入临时存储
factory.setSizeThreshold(MEMORY_THRESHOLD);
//设定临时文件的存储路径
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//ServletFileUpload 处理同意HTML文件中多文件上传的类,继承自FileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
//设置允许上传文件的最大大小
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = getServletContext().getRealPath("")+File.separator +UPLOAD_DIRECTORY;
//根据存储路径生成文件夹
File uploadDir = new File(uploadPath);
if(!uploadDir.exists()){
uploadDir.mkdir();
}
try{
List<FileItem> formItems = upload.parseRequest(request);
if(formItems!=null && formItems.size()>0){
for(FileItem item:formItems){
if(!item.isFormField()){
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
System.out.println("filePath" + filePath);
File storeFile = new File(filePath);
//写入文件
item.write(storeFile);
request.setAttribute("message", "Upload has been done successfully!");
}
}
}
}catch (Exception ex){
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}
}
3:message.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Result</title>
</head>
<body>
<center>
<h2>${message}</h2>
</center>
</body>
</html>
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Result</title>
</head>
<body>
<center>
<h2>${message}</h2>
</center>
</body>
</html>
4: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">
<display-name>FileUploadServletExample</display-name>
<servlet>
<display-name>FileUploadServlet</display-name>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.mdcl.bgctv.fileManage.action.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/uploadFile</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<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">
<display-name>FileUploadServletExample</display-name>
<servlet>
<display-name>FileUploadServlet</display-name>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.mdcl.bgctv.fileManage.action.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/uploadFile</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
效果如下: