Chinaunix首页 | 论坛 | 博客
  • 博客访问: 177286
  • 博文数量: 39
  • 博客积分: 1548
  • 博客等级: 上尉
  • 技术积分: 410
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-28 19:16
文章分类

全部博文(39)

文章存档

2011年(34)

2010年(5)

我的朋友

分类: Java

2011-01-07 09:10:35

文件: FileUpload.rar
大小: 230KB
下载: 下载
文件: FileUpload2.rar
大小: 206KB
下载: 下载
使用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(
"
  • "+str+"'>"+str+"
  • ");
                            }
                        }
                    
    %>
                    
    ul>
                
    fieldset>
            
                

                
    <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(
    "
  • "+str+"'>"+str+"
  • ");
                            }
                        }
                    
    %>
                    
    ul>
                
    fieldset>
            
                

                
    <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">

    script>
    html>


    阅读(4065) | 评论(0) | 转发(0) |
    给主人留下些什么吧!~~