Apache Commons FileUpload实现多文件上传

java web开发中,文件的上传是最常用的功能之一,快速实现文件上传功能对程序员来说是一项必备技能.如果你现在还是在自己埋头写程序来实现上传功能很难满足现代软件开发中所要求的快速性.下面通过一个实例介绍第三方组件(Apache Commons FileUpload)实现文件的上传.</span>

首先来看前端上传jsp页面:

<%@ page language="java" contentType="text/html; charset=GB18030"  
        pageEncoding="GB18030"%>   
    <%  
        String path = request.getContextPath();  
        String basePath = request.getScheme() + "://"  
            + request.getServerName() + ":" + request.getServerPort()  
            + path + "/";     
    %>  
    <html>  
        <head>  
            <title>index.html</title>  
      
            <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
            <meta http-equiv="description" content="this is my page">  
            <script language="javascript" src="jquery-1.4.2.min.js" type="text/javascript"></script>  
            <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  
        </head>  
        <body>      
            <form id="uploadform" name="uploadform" method="POST" action="http://localhost/docinadmin/lxz/upload.do"    
                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="x" size="40" type="file">  
                    </td>  
                </tr>  
                 <tr>  
                     <td width="100%" colspan="2">  
                        文件3:<input name="x" 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>


在<form>标签中一定要注明ENCTYPE="multipart/form-data",enctype属性表示这个表单提交时的编码方式,默认情况下是application/x-www-form-urlencoded,这种编码方式对于一般的文本数据传递是没有任何问题的,但是如果我们的页面用于文件上传那么这样的编码方式显然是可以的,我们是不能够将需要上传的物理文件通过文本方式进行上传的,所以必须将该属性的值改为multipart/form-data,表示此表单以二进制的方式进行数据传递。所以经此编码后的表单数据在后台代码中是不能够通过request.getParameter()方式来取得的。表单中的数据具体是怎样取得的我们不需要关心,第三方组件已经帮我们封装好了,我们只需要在后台代码中使用就可以了。下面我们来看后台代码是如何实现文件上传的。

后台代码实现文件上传:

public class LxzController extends MultiActionController{
	private File uploadPath;  
	private File tempPath;  
	public ModelAndView upload(HttpServletRequest request, HttpServletResponse response) throws Exception{
		init();
		//判断是否是多数据段提交格式  
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
        if(isMultipart){  
            DiskFileItemFactory factory = new DiskFileItemFactory();  
            // 设置文件的下限  
            factory.setSizeThreshold(4096);  
            // 设置中转目录  
            factory.setRepository(tempPath);  
      
            ServletFileUpload upload = new ServletFileUpload(factory);  
            //设置上传文件的上限  
            upload.setSizeMax(1000000 * 20);  
            try {  
                List fileItems = upload.parseRequest(request);  
                String itemNo = "";  
                for (Iterator iter = fileItems.iterator(); iter.hasNext();) {  
                    FileItem item = (FileItem) iter.next();  
                      
                    //是普通的表单输入域  
                    if(item.isFormField()) {  
                        if ("ceshi".equals(item.getFieldName())) {  
                            itemNo = item.getString();  
                            System.out.println("这是我的测试-------" + item.getFieldName());  
                        }  
                    }  
                    //是否为input="type"输入域  
                    if (!item.isFormField()) {  
                        String fileName = item.getName();  
                        long size = item.getSize();  
                        if ((fileName == null || fileName.equals("")) && size == 0) {  
                            continue;  
                        }  
                        //截取字符串 如:C:\WINDOWS\Debug\PASSWD.LOG  
                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());  
                        item.write(new File(uploadPath, fileName));  
                    }  
               }  
           }finally{
        	   
           }
        }
		return null;
	}
	
	public void init() {  
        uploadPath = new File(getServletContext().getRealPath("upload"));  
        System.out.println("uploadPath=====" + uploadPath);  
        //如果目录不存在  
        if (!uploadPath.exists()) {  
            //创建目录  
            uploadPath.mkdir();  
        }  
          
        //临时目录  
        tempPath = new File(getServletContext().getRealPath("temp"));  
        if (!tempPath.exists()) {  
            tempPath.mkdir();  
        }  
    }  
}


总结在整个代码编写过程中遇到的问题,需要引起大家注意的地方有以下几点:

1.servlet路径的配置。无论是在action属性中还是用js提交表单,所写的servlet路径一定要与配置文件中的url-pattern路径相一致。否则一定会出现404错误。

2.enctype属性一定要设置成multipart/form-data格式,否则后台不能获取所要上传的物理文件的二进制数据表示。

3.servlet的创建并不是固定的,可以是在Tomcat启动的时候也可以是在请求该Servlet的时候,如果在配置文件中写明<load-on-startup>的值是一个大于0的数,则tomcat在启动时就会创建servlet,如果没有设置这个属性,则是第一次访问时创建。

只要在实现该功能的时候注意以上几点,相信轻松搞定文件上传将不成问题。



带进度条的上传文档

http://blog.csdn.net/zhanglu201112/article/details/11707985

http://blog.csdn.net/hxlzpnyist/article/details/7601611

源代码:

http://download.csdn.net/detail/lxizh11/8068185

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值