天天看點

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) 進行多檔案選擇:

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

                                           圖1

2) 上傳進度顯示

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

                                      圖2

下面進行具體的操作:

第一步,要進行下面的過程,必須先準備好Flash插件和SwfUpload元件。

1) Flash插件:相信大家的浏覽器早已經安裝過了,請檢查版本,盡量使用最新的的flash插件。

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

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

1.主要目錄結構

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

2. 檔案上傳用到的js腳本檔案。

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

3. swfupload目錄中的檔案

WEB版一次選擇多個檔案進行批量上傳(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" target="_blank" rel="external nofollow" 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="取消全部上傳" οnclick="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>

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

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

                                     圖3.

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 =@"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)

    {

        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>

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

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

 最後的關于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這個檔案。

希望對大家有所幫助。

applicationdemo.net_vs2010.rar

轉載請注明本文位址: WEB版一次選擇多個檔案進行批量上傳(swfupload)的解決方案

繼續閱讀