春风博客

春天里,百花香...

导航

<2008年4月>
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

统计

公告

MAIL: junglesong@gmail.com
MSN: junglesong_5@hotmail.com

Locations of visitors to this page

常用链接

留言簿(11)

随笔分类(224)

随笔档案(126)

个人软件下载

我的其它博客

我的邻居们

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜

使用commons-fileupload实现单个和多个文件上传

对于实现文件上传功能来说,Commons-fileupload组件是一个不错的选择,本文使用它实现了单个文件及多个文件上传,这里将实现过程写出来与大家共享。

1.单个文件上传。
页面代码:
       
....
<div id="content">
            
<fieldset><legend>下載列表</legend>
                
<ul>
                
<%
                    List
<String> downloadList=(List<String>)request.getAttribute("downloadList");    
                    
                    
if(downloadList!=null){
                        
for(String str:downloadList){    
                            out.print(
"<li><a href='DownloadFile?file="+str+"'>"+str+"</a></li>");
                        }
                    }
                
%>
                
</ul>
            
</fieldset>
        
            
<!-- enctype属性为表单定义了MIME编码方式,上传文件的表单enctype属性必须如此设置 -->
            
<form method="post" action="UploadFile" enctype="multipart/form-data" >
            
<p><input type="text" name="fileIntro" value="" />文件介绍</p>
            
<p><input type="file" name="myfile1" value="浏览文件" /></p>
            
<p><input type="submit" value="上传"/></p>
            
</form>
        
</div>....
在上传表单中,既有普通文本域也有文件上传域,注意在Servlet中取它们和平常的做法不同:
Servlet代码:
package com.sitinspring.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sitinspring.util.UploadUtil;

/**
 * 用于文件上传处理的Servlet
 * 
@author sitinspring
 *
 * @date 2008-2-12
 
*/
public class UploadFileServlet extends HttpServlet {
    
private static final long serialVersionUID = 56890894234786L;

    @SuppressWarnings(
"unchecked")
    
public void doPost(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, java.io.IOException {
        request.setCharacterEncoding(
"UTF-8");

        
// 文件上傳部分
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        
        
if (isMultipart == true) {
            
try {
                FileItemFactory factory 
= new DiskFileItemFactory();
                ServletFileUpload upload 
= new ServletFileUpload(factory);
                
                
// 得到所有的表单域,它们目前都被当作FileItem
                List<FileItem> fileItems = upload.parseRequest(request);
                Iterator
<FileItem> iter = fileItems.iterator();
                
                
// 依次处理每个表单域
                while (iter.hasNext()) {
                    FileItem item 
= (FileItem) iter.next();
                    
                    
if(item.isFormField()){
                        
// 如果item是正常的表单域
                        String name = item.getFieldName();
                        String value 
= item.getString();
                        System.out.print(
"表单域名为:"+name+"表单域值为:"+value);
                    }
                    
else{
                        
// 如果item是文件上传表单域
                        
                        
// 获得文件名及路径
                        String fileName = item.getName();
                        
if (fileName != null) {
                            File fullFile 
= new File(item.getName());                            
                                                        
                            
// 如果文件存在则上传
                            if(fullFile.exists()){
                                File fileOnServer 
= new File(UploadUtil.getUploadPath(),
                                        fullFile.getName());
                                item.write(fileOnServer);
                                
                                System.out.println(
"文件"+fileOnServer.getName()+"上传成功");
                            }
                        }
                    }
                }                
            } 
catch (Exception e) {
                e.printStackTrace();
            }
        } 
else {
            System.out.println(
"the enctype must be multipart/form-data");
        }
        
        
// 取得服务器中已有文件的下載列表
        List<String> fileListInServer=new ArrayList<String>(); 
        
        File dir 
= new File(UploadUtil.getUploadPath());        
        String[] children 
= dir.list();
        
if (children != null) {
            
for (int i=0; i<children.length; i++) {
                fileListInServer.add(children[i]);                
            }
        }
        
        request.setAttribute(
"downloadList", fileListInServer);

        
// 跳回原頁面
        RequestDispatcher dispatcher = request
                .getRequestDispatcher(
"/web/page/uploadtoserver.jsp");
        dispatcher.forward(request, response);
        
return;
    }

    
public void doGet(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, java.io.IOException {
        doPost(request, response);
    }
}

从上面的代码可以看出,无论是否文件上传表单域都被当成了FileItem来处理,要区别开来使用isFormField()方法即可,返回真是常规表单域,返回假则是文件上传表单域。

2.多个文件上传到服务器端。

这里采用JS动态生成几个文件上传表单域即可,Servlet无需改变。
多文件上传页面代码如下:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@page language="java" import="java.util.List"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>上传多個文件到服务器</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" rev="stylesheet" href="web/css/style.css"
    type
="text/css" />
</head>

<body>
    
<div id="bodyDiv">
        
<div id="header">
            
<jsp:include page="/web/page/branch/header.jsp"/>
        
</div>
        
<div id="sidebar">
            
<jsp:include page="/web/page/branch/sidebar.jsp"/>
        
</div>
        
<div id="content">
            
<fieldset><legend>下載列表</legend>
                
<ul>
                
<%
                    List
<String> downloadList=(List<String>)request.getAttribute("downloadList");    
                    
                    
if(downloadList!=null){
                        
for(String str:downloadList){    
                            out.print(
"<li><a href='DownloadFile?file="+str+"'>"+str+"</a></li>");
                        }
                    }
                
%>
                
</ul>
            
</fieldset>
        
            
<!-- enctype属性为表单定义了MIME编码方式,上传文件的表单enctype属性必须如此设置 -->
            
<form name="uploadForm" method="post" action="UploadFile" enctype="multipart/form-data" >
            
<p><input type="button" value="增加上传按钮" onclick="addUploadButton()"/></p>
            
<p><input type="file" name="myfile1" value="浏览文件" /></p>
            
<p><input type="submit" value="上传"/></p>
            
</form>
        
</div>
        
<div id="footer">
            
<jsp:include page="/web/page/branch/footer.jsp"/>
        
</div>
    
</div>
</body>

JS代码:
<script LANGUAGE="JavaScript">
<!--
var count=1;

function addUploadButton(){    
    
// 按ID找到FOrm
    var uploadForm=document.getElementById("uploadForm");    
    
    
// 创建P元素
    var pNode=document.createElement("p");
    
    
// 累加Count以观察次数
    count=count+1;
    
    pNode.innerHTML
="<input type='file' name='myfile"+count+"' value='浏览文件'/>";
    
    
// 将P元素添加到body中
    uploadForm.appendChild(pNode);
}

//-->
</script>
</html>


实例代码:
http://www.blogjava.net/Files/sitinspring/FileUpload20080412145412.rar



posted on 2008-04-12 14:16 sitinspring 阅读(33982) 评论(13)  编辑  收藏 所属分类: Web开发

评论

# re: 使用commons-fileupload实现单个和多个文件上传 2008-04-14 17:21 anthony.rao

会不会有中文问题?  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传 2008-04-14 17:22 anthony.rao

就是下载的时候.用href直接连过去 ,要是文件名称是中文的话,有问题吗?  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传 2008-04-14 17:40 如坐春风

@anthony.rao

有中文问题,有待发掘一下.  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传 2008-12-03 13:21 e

中文问题有没有一个很好的解决办法 希望能指教下  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传 2009-03-04 11:45 zth

我也来顶一个。楼主好样的。。。扰屏对不起楼主,顶下..本人自己开培训部,
如果有感兴趣的同学,可以利用以下的联系方式联系我们,感谢大家的支持,欢迎咨询
福建省福州市战虎软件研发中心俱乐部===火热报名中……
战虎软件研发中心俱乐部欢迎您:走在软件开发安全的最前沿
本培训中心选修课程如下:
企业软件研发 软件架构设计 SQL注入 远程控制 木马研究 2D游戏研发 3D游戏研究 外挂研究 3D游戏研究 数据库设计
涉及的语言有:ASP.NET-C#......JAVA……C++……MASM32……PHP……FLASH AS3
地址:福建省福州市仓山区福建师范大学附近
如要咨询详情,拨打电话:15005086322进行咨询
联系方式:张老师15005086322|QQ:张老师920358479,张助理364823620
Email:zse555@fight-tiger.com|网址:http://www.fight-tiger.com
  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传[未登录] 2009-03-17 21:47 1

so good!~~  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传 2009-08-06 18:53 help

UploadUtil 在那里定义的?怎么找不到,能把代码贴出来吗  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传 2009-09-08 17:59 miffy

写的很详细,谢谢分享!  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传 2009-10-24 15:21 roundzheng

很不错,真的我调试了,很成功!  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传[未登录] 2010-03-31 16:41 df

ff  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传[未登录] 2010-03-31 16:42 df

fdfd  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传[未登录] 2010-03-31 16:42 df











































































































































































































fdfd



dfd
  回复  更多评论   

# re: 使用commons-fileupload实现单个和多个文件上传 2012-12-13 10:37 存储

@help
。。。我也想知道这个问题  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 
sitinspring(http://www.blogjava.net)原创,转载请注明出处.