用servlet编写的文件上传程序

采用了tomcat为发布器,调用了jarkarta的一个common-fileup组件,

着先配置好classpath,加上servlet.jar和commons-fileupload-1.0.jar,

然后把commons-fileupload-1.0.jar放到root下的web-inf/lib/下

编写up.java并编绎,放到web-inf/classes目录下

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;


public class up extends HttpServlet {
  private static final String CONTENT_TYPE = "text/html; charset=GB2312";
  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    PrintWriter out=response.getWriter();
    try {
    DiskFileUpload fu = new DiskFileUpload();
 // 设置允许用户上传文件大小,单位:字节,这里设为2m
 fu.setSizeMax(2*1024*1024);
 // 设置最多只允许在内存中存储的数据,单位:字节
 fu.setSizeThreshold(4096);
 // 设置一旦文件大小超过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);
      while (iter.hasNext()) {
       FileItem item = (FileItem)iter.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("d://" + m.group(1)));

           out.print(name+"&nbsp;&nbsp;"+size+"<br>");
           }
           catch(Exception e){
             out.println(e);
            
           }

        }
       else
       {
         throw new IOException("fail to upload");
       }
       }
   }
}
 catch (IOException e){
   out.println(e);
 }
 catch (FileUploadException e){
      out.println(e);

 }
 
  }
}

然后布署好web.xml,在其中加入

<servlet>
        <servlet-name>up</servlet-name>
        <servlet-class>up</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>up</servlet-name>
        <url-pattern>/fileup</url-pattern>
    </servlet-mapping>

好了现在再编写一个htm测试一下就ok了,注意url-pattern里面的路径必须跟表格中action的属性一样.

<html>
 <h1>文件上传演示</h1>

<form name="uploadform" method="POST" action="/fileup" 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>


</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值