1. 程式人生 > >WEB版一次選擇多個檔案進行批量上傳(swfupload)的解決方案

WEB版一次選擇多個檔案進行批量上傳(swfupload)的解決方案

功能完全支援ie和firefox瀏覽器!

      一般的WEB方式檔案上傳只能使用FileUpload控制元件進行一個檔案一個檔案的進行上傳,就算是批量上傳,也要把檔案一個一個的新增到頁面,無法如windows程式一樣,一次選擇多個檔案進行批量上傳。這樣在某些應用上就顯得很不人性化,有時候客戶希望能夠一次選擇很多檔案,然後讓系統把選擇的檔案全部上傳。

      這裡,就將針對這個問題提出一個比較完美的解決方案,利用的SwfUpload元件,讓客戶一次選擇多個檔案,然後將選擇的檔案上傳到伺服器上。

      關於SWFUpload的一些說明:

      1)  SWFUpload使用一個隱藏的Flash影片來控制檔案的選擇和上傳。

      2) JavaScript用來啟用檔案選擇對話方塊。此檔案選擇對話方塊是可以設定允許使用者選擇一個單獨的檔案或者是多個檔案。 選擇的的檔案型別也是可以被限制的,因此使用者只能選擇指定的適當的檔案,例如*.jgp;*.gif。

      3)  當選定檔案以後,每個檔案都會被驗證和處理。當Flash上傳檔案的時候,由開發人員預定義的Javascript事件會被定時觸發以便來更新頁面中的UI,同時還提供上傳狀態和錯誤資訊。

      4)  選定的檔案的上傳和它所在頁面、表單是獨立的。每個檔案都是單獨上傳的,這就保證了服務端指令碼能夠在一個時間點更容易地處理單個檔案。雖然Flash提供了上傳服務,但是頁面並不會提交或者重新載入。相比於標準的HTML Form,SWFUpload的使用方式更像是AJAX程式,頁面中的Form會和FLASH控制的檔案上傳單獨處理。
具體資訊可以訪問swfupload官方網站:http://www.swfupload.org/

讓我們先來看看客戶端的介面效果圖。(多選檔案,批量上傳,上傳進度顯示)

1) 進行多檔案選擇:

2) 上傳進度顯示

下面進行具體的操作:

第一步,要進行下面的過程,必須先準備好Flash外掛和SwfUpload元件。
1) Flash外掛:相信大家的瀏覽器早已經安裝過了,請檢查版本,儘量使用最新的的flash外掛。

2) SwfUpload:大家可以訪問swfupload官方網站:http://www.swfupload.org/,在這個網站上可以下載到元件與demo。

第二步,建立應用的目錄結構,我這個示例的目錄結構如圖:
1.主要目錄結構

2. 檔案上傳用到的js指令碼檔案。

3. swfupload目錄中的檔案


第三步,前臺部分準備客戶操作的WEB介面,如下[TestUploadFile2.aspx、uploadFile.aspx]

1) 前臺客戶端程式碼,其中TestUploadFile2.aspx的程式碼如下,TestUploadFile2.aspx.cs檔案中只使用預設的程式碼,不用新增任何程式碼。
TestUploadFile2.aspx
Html程式碼

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestUploadFile2.aspx.cs" Inherits="TestUploadFile2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<link href="css/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="swfupload/swfupload.js"></script>
<script type="text/javascript" src="simpledemo/js/swfupload.queue.js"></script>
<script type="text/javascript" src="simpledemo/js/fileprogress.js"></script>
<script type="text/javascript" src="simpledemo/js/handlers.js"></script>
<script type="text/javascript">
        var swfu;

        window.onload = function() {
            var settings = {
                flash_url : "swfupload/swfupload.swf",
                upload_url: "uploadFile.aspx",
                post_params: {
                    "ASPSESSID": "<%=Session.SessionID %>"
                },
                file_size_limit : "100 MB",
                file_types : "*.*",    //這是全部檔案都可以上傳,如果要限制只有某些檔案上傳,則可以這麼寫 file_types : "*.jpg;*.gif;*.png",


                file_types_description : "All Files",
                file_upload_limit : 100,
                file_queue_limit : 0,
                custom_settings : {
                    progressTarget : "fsUploadProgress",
                    cancelButtonId : "btnCancel"
                },
                debug: false,

                // Button settings

               //這兒是swfupload v2新增加的功能,由於flash player 10的安全性的提高所以增加了此功能。

              //在SWFUpload v2中,不能再使用html的button來觸發SWFUpload,必須使用定製的Button,這其中比較要注意的是,button不能再用css控制,需要用圖片來顯示

                button_image_url: "images/XPButtonNoText_160x22.png",
                button_placeholder_id: "spanButtonPlaceHolder",
                button_width: 160,
                button_height: 22,
                button_text: '<span class="button">&nbsp; &nbsp;選擇檔案 &nbsp;  &nbsp;<span class="buttonSmall">(2 MB Max)</span></span>',
                button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
                button_text_top_padding: 1,
                button_text_left_padding: 5,
                
                // The event handler functions are defined in handlers.js
                file_queued_handler : fileQueued,
                file_queue_error_handler : fileQueueError,
                file_dialog_complete_handler : fileDialogComplete,
                upload_start_handler : uploadStart,
                upload_progress_handler : uploadProgress,
                upload_error_handler : uploadError,
                upload_success_handler : uploadSuccess,
                upload_complete_handler : uploadComplete,
                queue_complete_handler : queueComplete    // Queue plugin event
            };

            swfu = new SWFUpload(settings);
         };
</script>
</head>
<body>
<div id="content">
    <h2>一次選擇多個檔案進行上傳</h2>
    <form id="form1" runat="Server">
    

    <div>
                <span id="spanButtonPlaceHolder"></span>
                <input id="btnCancel" type="button" value="取消全部上傳" onclick="swfu.cancelQueue();" disabled="disabled" style="margin-left: 2px; font-size: 8pt; height: 22px;" />
            </div>
                <p>&nbsp;</p>
            <div class="fieldset flash" id="fsUploadProgress">
            <span class="legend">Upload Queue</span>
            </div>
        <div id="divStatus">0 個檔案已經上傳</div>
        

    </form>
</div>
</body>
</html>

以上程式碼最後的顯示結果如圖:

2)後臺伺服器端程式碼:uploadFile.aspx檔案中使用預設的程式碼,不需要新增任何程式碼。uploadFile.aspx.cs檔案的程式碼如下:
uploadFile.aspx.cs


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class net_uploadFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      

         Response.CacheControl = "no-cache";
        string  s_rpath [email protected]"E:\WebSites\SWFUpload\demos\applicationdemo.net\"; //此處請自行修改成自己的目錄
      
              
                string Datedir = DateTime.Now.ToString("yy-MM-dd");
                string updir = s_rpath + "\\" + Datedir;
                if (this.Page.Request.Files.Count > 0)
                {
                    try
                    {

                        for (int j = 0; j < this.Page.Request.Files.Count; j++)
                        {

                            HttpPostedFile uploadFile = this.Page.Request.Files[j];

                            if (uploadFile.ContentLength > 0)
                            {
                                if (!Directory.Exists(updir))
                                {
                                    Directory.CreateDirectory(updir);
                                }
                                string extname = Path.GetExtension(uploadFile.FileName);
                                string fullname=DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString()+DateTime.Now.Day.ToString()+ DateTime.Now.Hour.ToString()+DateTime.Now.Minute.ToString()+DateTime.Now.Second.ToString();
                                string filename = uploadFile.FileName;

                                uploadFile.SaveAs(string.Format("{0}\\{1}", updir, filename));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Response.Write("Message"+ ex.ToString());
                    }

           
        }
    }
    }





第四步,如果使用以上程式碼,在具體的應用中不能使用或是ie可行,ff不行,則需要在Global.asax檔案中新增以下程式碼。
如果Global.asax檔案不存在,則請在應用的根目錄中建立。


<%@ Application Language="C#" %>

<script runat="server">

    void Application_BeginRequest(object sender, EventArgs e)
    {
        /* Fix for the Flash Player Cookie bug in Non-IE browsers.
         * Since Flash Player always sends the IE cookies even in FireFox
         * we have to bypass the cookies by sending the values as part of the POST or GET
         * and overwrite the cookies with the passed in values.
         *
         * The theory is that at this point (BeginRequest) the cookies have not been read by
         * the Session and Authentication logic and if we update the cookies here we'll get our
         * Session and Authentication restored correctly
         */

        try
        {
            string session_param_name = "ASPSESSID";
            string session_cookie_name = "ASP.NET_SESSIONID";

            if (HttpContext.Current.Request.Form[session_param_name] != null)
            {
                UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
            }
            else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
            {
                UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
            }
        }
        catch (Exception)
        {
            Response.StatusCode = 500;
            Response.Write("Error Initializing Session");
        }

        try
        {
            string auth_param_name = "AUTHID";
            string auth_cookie_name = FormsAuthentication.FormsCookieName;

            if (HttpContext.Current.Request.Form[auth_param_name] != null)
            {
                UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
            }
            else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
            {
                UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
            }

        }
        catch (Exception)
        {
            Response.StatusCode = 500;
            Response.Write("Error Initializing Forms Authentication");
        }
    }
    void UpdateCookie(string cookie_name, string cookie_value)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
        if (cookie == null)
        {
            cookie = new HttpCookie(cookie_name);
            HttpContext.Current.Request.Cookies.Add(cookie);
        }
        cookie.Value = cookie_value;
        HttpContext.Current.Request.Cookies.Set(cookie);
    }
           
</script>

第五步,在進行上傳之後的結果如圖:


最後的關於swfupload v2版的一些說明:

void selectFile()
不贊成使用,不相容Flash Player 10
彈出flash的檔案選擇對話方塊,只能選擇單個檔案。

void selectFiles()
不贊成使用,不相容Flash Player 10
彈出flash的檔案選擇對話方塊,可一次性選擇多個檔案。

關於上面的demo程式碼。其中swfupload使用的是v2.2 。

2012-12-27補充:

看了下面的留言,發現有些問題,我把Demo下載了下去,又自己試了一下,發現在IE9中上傳按鈕不可見,在IE7/8中可見。

2014-04-28補充:(感謝18樓的)

IE9不能顯示按鈕的我在別的網站上已經找到解決辦法,具體操作如下:
在swfupload.js中,找到SWFUpload.prototype.getFlashHTML
return ['<object id="', this.movieName, '" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',

把" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" 這個新增上去即可。我的程式碼已經新增上去了

我使用的VS2010。

對於以上專案進行了一些修改,在首頁中添加了指向Demo頁的標籤。

“一次選擇多個檔案進行上傳示例”是TestUploadFile2.aspx這個檔案。

希望對大家有所幫助。