转自http://blog.youkuaiyun.com/lcyong_/article/details/70227161
需要的jar
commons-fileupload-1.3.2
commons-io-1.4
servlet-api
特别注意commons-fileupload使用的时候必须和commons-io一起, 注意版本,其他版本容易报错
1 新建project并导入jar包
2 新建jsp文件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 >
- <html>
- <head>
- <base href=“<%=basePath%>”>
- <title>文件上传</title>
- <script type=“text/javascript” language=“JavaScript”>
- function prom() {
- window.open(“upload.jsp”,”_blank”,”height=400,width=500“)
- }
- </script>
- </head>
- <body>
- <button value=“上传文件”></button>
- <input type=“button” value=“upload” onclick=“prom()”/>
- </body>
- </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML >
<html>
<head>
<base href="<%=basePath%>">
<title>文件上传</title>
<script type="text/javascript" language="JavaScript">
function prom() {
window.open("upload.jsp","_blank","height=400,width=500")
}
</script>
</head>
<body>
<button value="上传文件"></button>
<input type="button" value="upload" οnclick="prom()"/>
</body>
</html>
3 点击上传文件的时候弹窗出对话框 新建jsp文件upload.jsp
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;
- %>
- <base href=“<%=basePath%>”>
- <form method=“post” action=“UploadServlet” enctype=“multipart/form-data”>
- <table width=“400” height=“200”>
- <tr>
- <td height=“20”></td>
- </tr>
- <tr>
- <td height=“20”></td>
- </tr>
- <tr>
- <td align=“center”>选择上传文件:(文件大小不要超过2MB)</td>
- </tr>
- <tr>
- <td align=“center”> <input type=“file” name=“file1” size=“50” value=“选择文件”></td>
- </tr>
- <tr>
- <td align=“center”> <input type=“submit” value=“开始上传”></td>
- </tr>
- <tr>
- <td height=“40”></td>
- </tr>
- </table>
- </form>
- 结果:<%=request.getAttribute(“result”)%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<base href="<%=basePath%>">
<form method="post" action="UploadServlet" enctype="multipart/form-data">
<table width="400" height="200">
<tr>
<td height="20"></td>
</tr>
<tr>
<td height="20"></td>
</tr>
<tr>
<td align="center">选择上传文件:(文件大小不要超过2MB)</td>
</tr>
<tr>
<td align="center"> <input type="file" name="file1" size="50" value="选择文件"></td>
</tr>
<tr>
<td align="center"> <input type="submit" value="开始上传"></td>
</tr>
<tr>
<td height="40"></td>
</tr>
</table>
</form>
结果:<%=request.getAttribute("result")%>
- package com.lh.servlet;
- import java.io.*;
- import java.util.*;
- import org.apache.commons.fileupload.*;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- import javax.servlet.*;
- import javax.servlet.http.*;
- public class UploadServlet extends HttpServlet {
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding(”UTF-8”);
- String Path=getServletContext().getRealPath(”/”)+“upload”; //定义上传文件的地址
- System.out.print(Path);
- File folder = new File(Path);
- if(!folder.exists())
- folder.mkdirs();
- String message=null;
- if(ServletFileUpload.isMultipartContent(request)){ //判断是否获取的是文件
- DiskFileItemFactory disk=new DiskFileItemFactory();
- disk.setSizeThreshold(20*1024); //设置内存可存字节数
- disk.setRepository(disk.getRepository()); //设置临时文件目录
- ServletFileUpload up=new ServletFileUpload(disk);
- int maxsize=200*1024*1024;
- List list=null;
- try{
- System.err.print(”—————–”);
- list=up.parseRequest(request); //获取上传列表
- }
- catch(Exception e){
- e.printStackTrace();
- }
- Iterator i=list.iterator(); //创建列表的迭代器
- while(i.hasNext()){
- FileItem fm=(FileItem)i.next(); //遍历列表
- if(!fm.isFormField()){
- String fname=fm.getName(); //获取文件名
- String filePath =fm.getName(); //获取文件全路径名
- String fileName=”“;
- int startIndex = filePath.lastIndexOf(“\\”);
- if(startIndex!=-1){ //对文件名进行截取
- fileName = filePath.substring(startIndex+1);
- }else{
- fileName=filePath;
- }
- if(fm.getSize()>maxsize){
- message=”文件太大了,不要超过200MB”;
- break;
- }
- String fileSize=new Long(fm.getSize()).toString();
- if((fname==null)||(fname.equals(“”))&&(fileSize.equals(“0”))){
- message=”文件名不能为空,文件大小也不能为零!”;
- break;
- }
- File saveFile=new File(Path,fileName);
- try{
- fm.write(saveFile);//向文件中写入数据
- message=”文件上传成功!”;
- }
- catch(Exception e1){
- e1.printStackTrace();
- }
- }
- }
- }
- request.setAttribute(”result”,message);
- RequestDispatcher rd=request.getRequestDispatcher(”upload.jsp”);
- rd.forward(request, response);
- }
- public void init(ServletConfig config) throws ServletException {
- super.init(config);
- }
- }
package com.lh.servlet;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.*;
import javax.servlet.http.*;
public class UploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String Path=getServletContext().getRealPath("/")+"upload"; //定义上传文件的地址
System.out.print(Path);
File folder = new File(Path);
if(!folder.exists())
folder.mkdirs();
String message=null;
if(ServletFileUpload.isMultipartContent(request)){ //判断是否获取的是文件
DiskFileItemFactory disk=new DiskFileItemFactory();
disk.setSizeThreshold(20*1024); //设置内存可存字节数
disk.setRepository(disk.getRepository()); //设置临时文件目录
ServletFileUpload up=new ServletFileUpload(disk);
int maxsize=200*1024*1024;
List list=null;
try{
System.err.print("-----------------");
list=up.parseRequest(request); //获取上传列表
}
catch(Exception e){
e.printStackTrace();
}
Iterator i=list.iterator(); //创建列表的迭代器
while(i.hasNext()){
FileItem fm=(FileItem)i.next(); //遍历列表
if(!fm.isFormField()){
String fname=fm.getName(); //获取文件名
String filePath =fm.getName(); //获取文件全路径名
String fileName="";
int startIndex = filePath.lastIndexOf("\\");
if(startIndex!=-1){ //对文件名进行截取
fileName = filePath.substring(startIndex+1);
}else{
fileName=filePath;
}
if(fm.getSize()>maxsize){
message="文件太大了,不要超过200MB";
break;
}
String fileSize=new Long(fm.getSize()).toString();
if((fname==null)||(fname.equals(""))&&(fileSize.equals("0"))){
message="文件名不能为空,文件大小也不能为零!";
break;
}
File saveFile=new File(Path,fileName);
try{
fm.write(saveFile);//向文件中写入数据
message="文件上传成功!";
}
catch(Exception e1){
e1.printStackTrace();
}
}
}
}
request.setAttribute("result",message);
RequestDispatcher rd=request.getRequestDispatcher("upload.jsp");
rd.forward(request, response);
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
}
5 在web.xml文件中配置如下:
- <servlet>
- <description>UploadServlet</description>
- <display-name>UploadServlet</display-name>
- <servlet-name>UploadServlet</servlet-name>
- <servlet-class>com.lh.servlet.UploadServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>UploadServlet</servlet-name>
- <url-pattern>/UploadServlet</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
<servlet>
<description>UploadServlet</description>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.lh.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>