分享

使用commons-fileupload例子--孤独的日子

 zhuge 2006-08-07




 

package com.pdw.servlet;

import java.io.*;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.*;

import java.util.regex.*;
import java.util.*;

public class FileUpServlet extends HttpServlet {
 
 private static final String CONTENT_TYPE="text/html;charset=utf-8";
 /**
  * Constructor of the object.
  */
 public FileUpServlet() {
  super();
 }

 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }

 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  * @throws FileUploadException
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType(CONTENT_TYPE);
  PrintWriter out=response.getWriter();
  DiskFileUpload dfu=new DiskFileUpload();
  dfu.setSizeMax(2*1024*1024);
  dfu.setSizeThreshold(4096);//最多允许在内存中存放4096个字节
  dfu.setRepositoryPath("c:/temp"); //当内存中存放的字据超过setSizeThreshold()所设定的值时,
                             //文件存放到硬盘目录
  try{
  List fileitems=dfu.parseRequest(request);
  Iterator it=fileitems.iterator();
  String regExp=".+\\\\(.+)$"; //正则匹配,去掉路径取文件名.
  String errortype[]={".exe",".com",".cgi",".asp"};
  Pattern p=Pattern.compile(regExp);
  
  while(it.hasNext()){
   FileItem fileitem=(FileItem)it.next();
//   忽略不是文件域的元素.
   if(!fileitem.isFormField()){
    String name=fileitem.getName();
    long size=fileitem.getSize();
    if("".equals(name)||size==0){
     continue;
    }
    System.out.println(name);
    Matcher m=p.matcher(name);
    boolean result=m.find();
    if(result){
     for(int i=0;i<errortype.length;i++){
      if(m.group(1).endsWith(errortype[i])){
       throw new IOException(name+" wrong type");
      }
     }
     System.out.println("---------------------------A");
     try{
      fileitem.write(new File("C:/upload/"+m.group(1)));
      out.println(name+"--->"+size);
     }catch(Exception e){
      out.print(e);
     }
     System.out.println("----------------B");
    }else{
     throw new IOException("文件上传失败");
    }
   }
  }
  
  }catch(Exception e){
   System.out.println(e.toString());
  }
 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  * @throws FileUploadException
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  doGet(request,response);
 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occure
  */
 public void init() throws ServletException {
  // Put your code here
 }

}

====================================================


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP ‘fileup.jsp‘ starting page</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">
   
    <!--
    <link rel="stylesheet" type="text/css" href="/styles.css">
    -->
  </head>
 
  <body>
    <center>文件上传例子</center>
    <FORM action="servlet/FileUpServlet" method="post" enctype="multipart/form-data">
     <table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF">

        <tr><td width="100%" colspan="2">

                        文件1:<input name="x" size="40" type="file">

        </td></tr>

        <tr><td width="100%" colspan="2">

                        文件2:<input name="y" size="40" type="file">

        </td></tr>

        <tr><td width="100%" colspan="2">

                        文件3:<input name="z" size="40" type="file">

        </td></tr>

        </table>

        <br/><br/>

        <table>

        <tr><td align="center"><input name="upload" type="submit" value="开始上传"/></td></tr>

       </table>

     
    </FORM>
  </body>
</html>


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多