common-fileupload组件

本文介绍了一个实用的common-fileupload组件,该组件能够高效地上传大文件,包括300M以上文件的本地及异地上传。通过配置DiskFileUpload参数,如设置最大文件大小、内存阈值及临时存储路径等,可以实现文件的安全有效上传。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2.common-fileupload组件挺好用的,也能够上传大文件,我试过,300M以上的文件上传本地传非常快,异地测试也能够上传成功.首先要下载org.apache.commons.fileupload包和org.apache.commons.io包下面是我的servletpackage com.kinstar.issuing.action; import java.io.IOException;import javax.servlet.Servlet;import javax.servlet.ServletException;import java.io.*;import java.sql.SQLException;import java.util.*;import java.text.*;import javax.servlet.*;import javax.servlet.http.*;import java.util.regex.*;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.DiskFileUpload;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;import com.kinstar.issuing.objects.t_user;import com.kinstar.issuing.operation.UserOperation;import com.kinstar.issuing.program.programService;import com.kinstar.issuing.session.SessionGloble;import com.kinstar.issuing.util.StringUtil;/** * @version  1.0 * @author gyf */public class uploadProgramAction extends HttpServlet{  private static final String CONTENT_TYPE = "text/html; charset=GB2312";   /**  * 处理GET请求  */  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    doPost(request,response);  }   /**  * 响应POST请求  */  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   // 变量定义    response.setContentType(CONTENT_TYPE);    HttpSession modifysession=request.getSession();    SessionGloble logonUser;    logonUser=(SessionGloble)modifysession.getAttribute("UserInfo");       if(logonUser==null){       response.sendRedirect("mainindex.jsp");    }    t_user userinfo=new t_user();    UserOperation user=null;    try {     user = new UserOperation();    } catch (Exception e1) {    // TODO 自动生成 catch 块    e1.printStackTrace();    }    try {     userinfo=user.getUser(logonUser.getUserId());    } catch (Exception e2) {    // TODO 自动生成 catch 块    e2.printStackTrace();    }     //System.out.println("figure="+userinfo.getUserFigure());     PrintWriter out=response.getWriter();     DateFormat updf = new SimpleDateFormat("yyyyMMddHHmm");     String updateTime = updf.format(new Date());     int isNeed = 0;     String IsCheck="0";      //省农行用户上传的节目必需显示,且审批已经合格     if(userinfo.getUserFigure().equals("1")){     isNeed = 1;     IsCheck = "1";     }     else{     isNeed = 0;     IsCheck = "0";     }    int type=0;    String avaTime="";    String screen="";    int fileTime=0;    int fileTimeReal=0;    int circle=0;    String picSwitch="";    String deleState="1";    String backPic="";       String fieldName="";    String finalName="";    String fileNameReal="";    long size=0;    String name="";     try {    DiskFileUpload fu = new DiskFileUpload();    // 设置允许用户上传文件大小,单位:字节,这里设为2m    fu.setSizeMax(5*1024*1024*1024);    // 设置最多只允许在内存中存储的数据,单位:字节    fu.setSizeThreshold(10*1024*1024);    // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录    fu.setRepositoryPath("C://WINDOWS//Temp//");    //开始读取上传信息    List fileItems = fu.parseRequest(request);    //依次处理每个上传的文件    Iterator iter = fileItems.iterator();          //正则匹配,过滤路径取文件名    String regExp=".+////(.+)$";     //过滤掉的文件类型    String[] errorType={".exe",".com",".cgi",".asp"};         Pattern p = Pattern.compile(regExp);    StringUtil su = new StringUtil();          while (iter.hasNext()) {      FileItem item = (FileItem)iter.next();           if(item.isFormField()) {       // 获得表单域的名字        fieldName = item.getFieldName();        // 如果表单域的名字是name…        if(fieldName.equals("type"))            type = Integer.parseInt(item.getString());             }      if (!item.isFormField()) {       name = item.getName();       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");        }        }             DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");                String date = df.format(new Date());       fileNameReal=date+m.group(1);       finalName=date+Math.round(Math.random()*10000)+fileNameReal.substring(fileNameReal.indexOf("."));        //保存上传的文件到指定的目录          //在下文中上传文件至数据库时,将对这里改写        item.write(new File(getServletContext().getRealPath(".//ads//")+finalName));        //out.print(finalName+size);        }       else       {      throw new IOException("fail to upload");             }       }      if(item.isFormField()) {     // 获得表单域的名字     fieldName = item.getFieldName();     if(fieldName.equals("avaTime"))      avaTime=item.getString();     if(fieldName.equals("screen"))      screen=item.getString();     if(fieldName.equals("fileTime"))      fileTime = Integer.parseInt(item.getString());     if(fieldName.equals("fileTimeReal"))      fileTimeReal = Integer.parseInt(item.getString());     if(fieldName.equals("circle"))      circle = Integer.parseInt(item.getString());      if(fieldName.equals("switchPic"))        picSwitch = item.getString();             }          }     }catch (IOException e){       out.println(e);     }catch (FileUploadException e){       out.println(e);     } catch (Exception e) {    // TODO 自动生成 catch 块     e.printStackTrace();     }     if(finalName.equals("")){       response.sendRedirect("fail.jsp");     }     else{   try {    programService ps = new programService();    ps.insertProgram(userinfo.getUserId(),updateTime,type,finalName,size,isNeed,avaTime,deleState,IsCheck,userinfo.getCity(),backPic,screen,fileTime,fileTimeReal,picSwitch,circle,userinfo.getUserFigure(),new String(fileNameReal.getBytes("GB2312"),"ISO8859-1"));    response.sendRedirect("program.jsp?dopass=true");    } catch (Exception e3) {   // TODO 自动生成 catch 块    e3.printStackTrace();   }     }   }}文章引用自:http://www.blogjava.net/coffeecat/archive/2006/08/18/64384.aspx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值