servlet 实现多个文件上传,完整代码:
html 代码:
参考 [url]http://apps.hi.baidu.com/share/detail/23055527[/url]
package com.commpim.performance;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class for Servlet: UploadFile2Servlet
*
*/
public class UploadFilet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
//用于存放上传文件的目录
private String uploadPath="E:\\upFile\\";
private File tempPath=new File("E:\\upFile\\temp");
/**
* 初始化Servlet,确保需要使用的目录都被建立<br>
* @throws javax.servlet.ServletException
*/
@Override
public void init() throws ServletException{
if(!new File(uploadPath).isDirectory())
new File(uploadPath).mkdir();
if(!tempPath.isDirectory())
tempPath.mkdir();
}
/**
* 销毁Servelt
*/
public void destory(){
super.destroy();
}
/**
* @param request
* @param response
* @throws javax.servlet.ServletException
* @throws java.io.IOException
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//创建一个上传项目工厂,并设置其缓存数据大小和临时文件保存位置
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setSizeThreshold(4096);
factory.setRepository(tempPath);
//使用项目工厂创建一个ServletFileUpload对象,用于解析文件上传请求
//并设置可以上传的文件的最大字节数,超过会抛出异常
ServletFileUpload upload=new ServletFileUpload(factory);
upload.setSizeMax(1000000);
upload.setHeaderEncoding("utf-8");
List fileItems=null;
try{
//开始读取上传信息
fileItems=upload.parseRequest(request);
//依次处理每一个上传的文件
Iterator itor=fileItems.iterator();
//正则匹配,过滤路径取文件名
String regExp=".+\\\\(.+)$";
//过滤文件类型
String[] errorType={".exe",".com",".cgi",".asp"};
Pattern p=Pattern.compile(regExp);
while(itor.hasNext()){
FileItem item=(FileItem)itor.next();
//忽略其他不是文件域的所有其他表单信息
if(!item.isFormField()){
String name=item.getName();
long size=item.getSize();
if((name==null||name.equals(""))&&size==0)
continue;
Matcher m=p.matcher(name);
boolean result=m.find();
//如果是允许上传的文件类型就执行上传操作
if(result){
for(int temp=0;temp<errorType.length;temp++){
if(m.group(1).endsWith(errorType[temp])){
throw new IOException(name+":wrong type");
}
}
try{
//保存文件到指定的目录,如果是保存到数据库,改写这里
item.write(new File(uploadPath,m.group(1)));
}catch(Exception e){
}
}else{
throw new IOException("fail to upload");
}
}
}
}catch(IOException e){
e.printStackTrace();
}catch(FileUploadException e1){
e1.printStackTrace();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "cliff";
}
// </editor-fold>
}
html 代码:
<html>
<body>
<form name="fileform" method="post" action="UploadFilet"
style="display: none; font-weight: bold;"
enctype="multipart/form-data">
<div align="center">
<table width="421" border="1" bordercolor="#C5D6FC"
id="urltable">
<tr>
<td width="421">
<div align="center">Upload Files</div>
</td>
</tr>
<tr>
<td><input type="file" name="url_1" size="62" /></td>
</tr>
<tr>
<td><input name="url_2" type="file" size="62" /></td>
</tr>
</table>
</div>
<p align="center"><input type="submit" name="Submit"
value="Submit" /></p>
</form>
</body>
</html>
参考 [url]http://apps.hi.baidu.com/share/detail/23055527[/url]