星期四, 10月 23, 2014

[C#] FileUpload 多選

FileUpload 多選練習
  • dotNet 4.5:FileUpload AllowMultiple屬性 
  • dotNet 4.5 前版本:Panel 內有多個 FileUpload 控件
using System.IO;

namespace MultiUpload
{
    public partial class _default : System.Web.UI.Page
    {
        string serverPath = @"D:\FileUploadDemo";
        string serverFilePath = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // 設定該屬性 FileUpload 就具有多選檔案功能
                FU1.AllowMultiple = true;
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FU1.HasFiles == false) return;

            foreach (HttpPostedFile file in FU1.PostedFiles)
            {
                serverFilePath = Path.Combine(serverPath, file.FileName);
                try
                {
                    // 網友發現該錯誤
                    // FU1.SaveAs(serverFilePath);
                    file.SaveAs(serverFilePath);
                    lblMessage.Text = "上傳成功";
                }
                catch (Exception ex)
                {
                    lblMessage.Text = ex.Message;
                }
            }
        }

        protected void btnPanelUpload_Click(object sender, EventArgs e)
        {
            // 搜尋 Panel 內的 FileUpload 控件
            foreach (FileUpload fu in plFU.Controls.OfType<fileupload>())
            {
                // 判斷有哪些 FileUpload 有選擇檔案
                if (fu.HasFile == false) continue;
                serverFilePath = Path.Combine(serverPath, fu.FileName);
                try
                {
                    fu.SaveAs(serverFilePath);
                    lblPanelMessage.Text = "上傳成功";
                }
                catch (Exception ex)
                {
                    lblPanelMessage.Text = ex.Message;
                }
            }
        }
    }
}
[C#] FileUpload 多選

3 則留言:

  1. dotNet 4.5:FileUpload AllowMultiple屬性
    上傳後檔案名稱不一樣,但檔案內容都一樣

    回覆刪除
  2. FU1.SaveAs(serverFilePath);
    改成
    file.SaveAs(serverFilePath);

    回覆刪除