asp.net中實現檔案批量上傳!你會了嗎?

來源:互聯網
上載者:User

  今天BOSS要求做一個批量上傳檔案的功能,忙活了半天,總算搞定,希望前輩們多加指點,下面來看一下(這裡是簡化版,只介紹了主要實現過程,沒有美化,勿怪!勿怪!):

單擊添加檔案,將自動添加FileUpload控制項。

單擊瀏覽分別選擇要上傳的多個檔案

單擊上傳檔案,完成檔案的上傳。

好了不多說,下面是代碼:

前台Default.aspx代碼

<%@ 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">    <title>批量上傳檔案</title></head><body>    <form id="form1" runat="server">    <div style="width:300px; margin:50px auto;">      <asp:Label ID="LblMessage" runat="server" Width="300px" ForeColor="#FF0033" Font-Bold="True" Font-Size="Small" />      <table border="1" bordercolor="gray" style="border-collapse: collapse;">        <tr>          <td style="text-align: center; font-size:10pt; font-weight:bold; color:DimGray;">             批量上傳檔案          </td>        </tr>        <tr>          <td>             <asp:Panel ID="Pan_UpFile" runat="server" Height="200px" ScrollBars="Auto" Width="250px">               <table id="Tab_UpDownFile" runat="server" cellpadding="0" cellspacing="0" enableviewstate="true">                  <tr>                     <td style="width: 100px; height: 30px">                        <asp:FileUpload ID="FileUpload1" runat="server"/>                     </td>                  </tr>              </table>            </asp:Panel>          </td>        </tr>        <tr>          <td>                    <asp:Button ID="BtnAdd" runat="server" Text="添加檔案" OnClick="BtnAdd_Click" BorderColor="Gray" BorderWidth="1px" />            <asp:Button ID="BtnUpFile" runat="server" OnClick="BtnUpFile_Click" Text="上傳檔案" BorderColor="Gray" BorderWidth="1px" />          </td>        </tr>      </table>     </div>    </form></body></html>

Default.aspx.cs代碼(注釋有一定說明,都能看懂吧?)

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Collections;//引入命名空間public partial class _Default : System.Web.UI.Page {    protected void Page_Load(object sender, EventArgs e)    {        if (!Page.IsPostBack)//首次執行頁面        {            SFUPC();        }    }    #region  該方法用於將當前頁面上傳檔案控制項集儲存到Session中    private void SFUPC()    {        ArrayList AL = new ArrayList();//動態增加數組        foreach (Control C in Tab_UpDownFile.Controls)        {            //在表格中尋找出FileUpload控制項添加到ArrayList中            if (C.GetType().ToString() == "System.Web.UI.HtmlControls.HtmlTableRow")            {                HtmlTableCell HTC = (HtmlTableCell)C.Controls[0];                foreach (Control FUC in HTC.Controls)                {                    if (FUC.GetType().ToString() == "System.Web.UI.WebControls.FileUpload")                    {                        FileUpload FU = (FileUpload)FUC;                        //設定FileUpload的樣式                        FU.BorderColor = System.Drawing.Color.DimGray;                        FU.BorderWidth = 1;                        //添加FileUpload控制項                        AL.Add(FU);                    }                }            }        }        //把ArrayList添加到Session中        Session.Add("FilesControls", AL);    }    #endregion    #region 該方法用於添加一個上傳檔案的控制項    private void InsertC()    {        //執行個體化ArrayList        ArrayList AL = new ArrayList();        this.Tab_UpDownFile.Rows.Clear(); //清除id為F表格裡的所有行        GetInfo();        //表示 HtmlTable 控制項中的 <tr> HTML 元素        HtmlTableRow HTR = new HtmlTableRow();        //表示 HtmlTableRow 對象中的 <td> 和 <th> HTML 元素        HtmlTableCell HTC = new HtmlTableCell();        //在儲存格中添加一個FileUpload控制項        HTC.Controls.Add(new FileUpload());        //在行中添加儲存格        HTR.Controls.Add(HTC);        //在表中添加行        Tab_UpDownFile.Rows.Add(HTR);        SFUPC();    }    #endregion    #region 該方法用於將儲存在Session中的上傳檔案控制項集添加到表格中    private void GetInfo()    {        ArrayList AL = new ArrayList();        if (Session["FilesControls"] != null)        {            AL = (ArrayList)Session["FilesControls"];            for (int i = 0; i < AL.Count; i++)            {                HtmlTableRow HTR = new HtmlTableRow();                HtmlTableCell HTC = new HtmlTableCell();                HTC.Controls.Add((System.Web.UI.WebControls.FileUpload)AL[i]);                HTR.Controls.Add(HTC);                Tab_UpDownFile.Rows.Add(HTR);            }        }    }    #endregion    #region 該方法用於執行檔案上傳操作    private void UpFile()    {        //擷取檔案夾路徑        string FilePath = Server.MapPath("./") + "File";        // 擷取用戶端上傳檔案的集合        HttpFileCollection HFC = Request.Files;        for (int i = 0; i < HFC.Count; i++)        {            //訪問指定的檔案            HttpPostedFile UserHPF = HFC[i];            try            {                //判斷檔案是否為空白                if (UserHPF.ContentLength > 0)                {                    //將上傳的檔案儲存體在指定目錄下                    UserHPF.SaveAs(FilePath + "\\" + System.IO.Path.GetFileName(UserHPF.FileName));                }            }            catch            {                LblMessage.Text = "上傳失敗!";            }        }        if (Session["FilesControls"] != null)        {            Session.Remove("FilesControls");        }        LblMessage.Text = "上傳成功!";    }    #endregion    #region 調用InsertC方法,實現添加FileUpLoad控制項的功能    protected void BtnAdd_Click(object sender, EventArgs e)    {        InsertC();//執行添加控制項方法        LblMessage.Text = "";    }    #endregion    #region 實現檔案上傳的功能    protected void BtnUpFile_Click(object sender, EventArgs e)    {        if (this.FileUpload1.PostedFile.FileName != "")        {            UpFile();//執行上傳檔案            SFUPC();        }        else        {             LblMessage.Text = "對不起,上傳檔案為空白,請選擇上傳檔案!";        }    }    #endregion}

完!

請讀者根據實際情況做適當修改!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.