Jquery.MultiFile.js和UpdatePannel實現多文件上傳


最近在項目中碰到了多文件上傳,用的是Jquery插件:Jquery.MultiFile.js,官網:http://www.fyneworks.com/jquery/multiple-file-upload/ ,由於在同一個頁面中用到了UpdatePannel,有用到了Jquery插件,這兩個混合用造成了多文件上傳插件失效,在網上搜索了一些結果,最終知道原因問題總算搞定;

今天做一個模擬環境來記錄下:

前台頁面代碼

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

<!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">
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery.MultiFile.js" type="text/javascript"></script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <script type="text/javascript" language="javascript">
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
        function EndRequestHandler(sender, args) {
            $('#attFile').MultiFile({
                list: '#att-list'
            });
        }  
    </script>
    <div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server"  UpdateMode="Conditional">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="btnAsyn" EventName="Click" />
                                <asp:PostBackTrigger ControlID="btnSyn" />
            </Triggers>
            <ContentTemplate>
                <input type="file" id="attFile" name="attFile" style="border: thin solid #C0c0c0;
                    margin: 1px 1px 1px 1px" accept="xls|xlsx|docx|doc|ppt|pptx|pdf|txt|gif|bmp|jpg|zip|avi|wmv"
                    class="multi" />
                <div id="att-list">
                </div>
                <asp:Button ID="btnAsyn" runat="server" Text="Asynchronous" OnClick="btnAsyn_Click" />//用來模擬會發操作
                <asp:Button ID="btnSyn" runat="server" Text="Synchronous" OnClick="btnSyn_Click" />//在UpdatePannel內部用按鈕提交表單
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:Button ID="btnUploadFile" runat="server" Text="Button" OnClick="btnUploadFile_Click" />//在UpdatePannel外部用按鈕提交表單
    </div>
    </form>
</body>
</html>
 
         

 

 

后台代碼:

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            this.Form.Enctype = "multipart/form-data";
        }
    }

    /// <summary>
    /// get current HttpContext all files 
    /// </summary>
    /// <returns></returns>
    private List<string> GetAttachement()//用來得到文件
    {
        System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

        if (files != null && files.Count > 0)
        {
            try
            {
                string filePath = "~/UploadFiles";
                string phyPath = HttpContext.Current.Request.MapPath(filePath);
                if (!Directory.Exists(phyPath))
                {
                    Directory.CreateDirectory(phyPath);//.Create();
                }
                List<string> fileNameString = new List<string>();

                for (int index = 0; index < files.Count; index++)
                {
                    System.Web.HttpPostedFile postedFile = files[index];
                    string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                    if (!String.IsNullOrEmpty(fileName))
                    {
                        string fileExtension = System.IO.Path.GetExtension(fileName);
                        DateTime now = DateTime.Now;
                        string strFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(fileName);
                        string saveName = strFileNameWithoutExtension + "_" + now.ToString("yyyyMMddHHmmss") + fileExtension;
                        postedFile.SaveAs(string.Format("{0}\\{1}", phyPath, saveName));

                        fileNameString.Add(saveName);
                    }
                }
                return fileNameString;
            }
            catch
            {
                return null;
            }
        }
        else
            return null;

    }
    protected void btnUploadFile_Click(object sender, EventArgs e)
    {
        List<string> files = GetAttachement();
        if (files!=null && files.Count>0)//在UpdatePannel外部提交后查看得到的文件個數
        {

        }
    }
    protected void btnAsyn_Click(object sender, EventArgs e)
    {

    }
    protected void btnSyn_Click(object sender, EventArgs e)
    {
        List<string> files = GetAttachement();
        if (files != null && files.Count > 0)//在UpdatePannel內部提交后,調試查看得到的文件個數
        {

        }
    }
}

初始化運行界面:

 

選擇兩個文件:

這個時候提交表單查看獲得的文件個數:

一共添加了兩個文件,獲得的文件個數是2

問題1:這個時候模擬一次異步回傳后在添加文件:單擊異步回傳按鈕,再進行添加文件,Jquery插件就會失效,不能添加文件,

失效后的截圖:

插件失效解決方案:

<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <script type="text/javascript" language="javascript">
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);//用這句話就能解決問題。詳細解釋請查看微軟官網:http://msdn.microsoft.com/en-us/library/bb383810(v=vs.100).aspx
        function EndRequestHandler(sender, args) {
            $('#attFile').MultiFile({//
                list: '#att-list'
            });
        }  
    </script>

 

添加以上腳本Jquery.MultiFile.js有能正常工作。

問題2:通過UpdatePannel外部的按鈕提交獲得文件沒有任何問題,但是當通過UpdaePannel內部的按鈕提交表單,總是獲得不到文件個數:

問題截圖如下:

 

問題2解決方案:設置UpdatePannel內部的按鈕為回傳性質的按鈕,代碼如下:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="btnAsyn" EventName="Click" />
                <asp:PostBackTrigger ControlID="btnSyn" />//一定要加上這句話,給按鈕設置回傳屬性
            </Triggers>

 

最后好葯注意一點,非常重要,是上傳文件比不可少的:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            this.Form.Enctype = "multipart/form-data";//在這里設置或者直接在表單屬性設置:<form id="form1" runat="server" enctype="multipart/form-data">
        }
    }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM