HttpFileCollection 實現多檔案上傳

weixin_30924079發表於2020-04-04

1 前臺程式碼
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>

<!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 id="Head1" runat="server">
    <title>批量上傳</title>
    <script src="jquery/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        var count = 1; //上傳元件個數
        $(function () {
            //新增上傳元件
            $("#btnAdd").click(function () {
                //                if ($("#DivUploads").find(":button").length >= 7) {
                //                    alert('最多隻能新增八個上傳元件!');
                //                    return;
                //                }
                var strHtml = '<span><input type="file" name="fileUpload" runat="server" />';
                strHtml += "<input type='button' οnclick='delUploadBtn(" + count + ")' value='刪除'/></span>";
                $("#DivUploads").append(strHtml);
                count++;
            });
        });
        //刪除上傳元件
        function delUploadBtn(index) {
            $("#DivUploads").find(":button").each(function () {
                var text = "" + $(this).attr("onclick");
                if (text.indexOf("delUploadBtn(" + index + ")") != -1) {
                    $(this).parent().remove();
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    &nbsp;&nbsp;
    <%-- <asp:LinkButton ID="btnAdd" runat="server">新增</asp:LinkButton>--%>
    <input type="button" id="btnAdd" value="新增" />
    <div id="DivUploads" style="border: 0px solid; width: 300px; height: auto;">
    </div>
    <asp:Button ID="btnUpload" runat="server" Text="上傳" OnClick="btnUpload_Click" />
    </form>
</body>
</html>


2 後臺程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }
    /// <summary>
    /// 上傳處理
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string filepath = Request.Form["fileUpload"];

       //上傳檔案儲存路徑 
        string savePath = Server.MapPath("UploadFiles") + "\\";   

        //提供對客戶端上載檔案的訪問
        HttpFileCollection uploadFiles = System.Web.HttpContext.Current.Request.Files;
        try
        {
            for (int i = 0; i < uploadFiles.Count; i++)
            {
                System.Web.HttpPostedFile postedFile = uploadFiles[i];
                string fileName = postedFile.FileName;//完整的路徑
                fileName = System.IO.Path.GetFileName(postedFile.FileName); //獲取到名稱
                string fileExtension = System.IO.Path.GetExtension(fileName);//檔案的副檔名稱
                string type = fileName.Substring(fileName.LastIndexOf(".") + 1);    //型別 
                if (uploadFiles[i].ContentLength > 0)
                    uploadFiles[i].SaveAs(savePath + fileName);
            }
        }
        catch (System.Exception Ex)
        {
            Response.Write(Ex);
        }
    }
}

還是整個執行的效果圖:

 

 

 

 

為了用著方便以及程式碼重用,可以新建一個客戶端控制元件,加到客戶端裡面去

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="uploadControl.ascx.cs" Inherits="Admin_userControl_uploadControl" %>
 <style type="text/css">
    #table_fileList{
        clear:left;
        border-top:1px solid #A2C1E0;
        border-left:1px solid #A2C1E0;
        border-spacing:0px;
    }
    #table_fileList td{
        border-right:1px solid #A2C1E0;
        border-bottom:1px solid #A2C1E0;
    }
    #table_fileList th{
        border-right:1px solid #A2C1E0;
        border-bottom:1px solid #A2C1E0;
    }
    </style>
    <script type="text/javascript">

        var count = 2; //上傳元件個數
        $(function() {
            //新增上傳元件 New method
            $("#btnAddUploadNew").click(function() {
                var fileName = GetUploadFileName();
                if (fileName == "") {
                    alert('上傳檔案不能為空!');
                    return;
                }
                else {
                    var fileCount = GetUploadFileCount();
                    if (!checkFile(fileName))//檢查檔案是否重複上傳
                    {
                        return;
                    }
                    var Html = "<tr><td>" + fileName + "</td><td><img src='../Images/cross.png' alt='刪除' οnclick='delUploadBtn(" + count + ")'/></td></tr>";
                    $("#uploadBody").append(Html);

                    var strHtml = '<span><input type="file" name="fileUpload" runat="server" /><input type="text" value="' + count + '" style="display:none" /></span>';
                    $("#DivUploads").find(":file").each(function() {
                        $(this).css("display", "none");
                    });
                    $("#DivUploads").append(strHtml);
                    if (fileCount == 4) {
                        $("#DivUploads span:last-child").find(":file").attr("disabled", "disabled");
                    }
                    count++;
                }
            });

        });

        //刪除上傳元件
        function delUploadBtn(index) {
            //刪除隱藏的上傳控制元件
            $("#DivUploads").find(":text").each(function() {
                if ($(this).attr("value") == "" + (index - 1)) {
                    $(this).parent().remove();
                    return;
                }
            });
            //New method刪除下方顯示的上傳檔案列表
            $("#uploadBody tr td").find("img").each(function() {
                var text = ""+$(this).attr("onclick");
                if (text.indexOf(index) != -1) {
                    $(this).parent().parent().remove();
                }
            });
            $("#DivUploads span:last-child").find(":file").attr("disabled", ""); //上傳控制元件恢復可用
        }


        //獲取上傳檔案的數量
        function GetUploadFileCount() {
            var count = 0;
            $("#uploadBody tr").each(function() {
                count++;
            });
            return count;
        }

        //獲取上傳檔名
        function GetUploadFileName() {
            var fileName = "";
            $("#DivUploads").find(":file").each(function() {
                if ($(this).css("display") != "none") {
                    fileName = $(this).val();
                    return;
                }
            });
            return fileName;
        }
        //檢查上傳檔案是否重複,以及副檔名是否符合要求
        function checkFile(fileName) {
            var flag = true;
            $("#uploadBody tr td").each(function() {
                if (fileName == $(this).text()) {
                    flag = false;
                    alert('上傳檔案中已經存在\'' + fileName + '\'!');
                    return;
                }
            });
            //檔案型別判斷
            var str = "jpg|jpeg|bmp|gif|doc|docx|xls|xlsx|txt";
            var fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1); //獲取上傳副檔名
            if (str.indexOf(fileExtName.toLowerCase()) == -1) {
                alert("只允許上傳格式為jpg,jpeg,bmp,doc,docx,xls,xlsx,txt的檔案。");
                flag = false;
            }
            return flag;
        }
       
    </script>
    
    <!--上傳控制元件列表begin-->
    <div id="DivUploads" style="height:auto;float:left;width:250px;">
      <span>
      <input id="file_first" type="file" name="fileUpload" runat="server"/>
      <input type="text" value="1" style="display:none" />
      </span>
    </div><input id="btnAddUploadNew" type="button" value="新增" />
  <!--上傳控制元件列表end-->
  <br/>
    <!--上傳檔案列表begin-->
    <table border="0" cellspacing="1" cellpadding="0" id="table_fileList" >
    <thead>
        <tr>
            <th style="width: 464px;" align="left">
                檔名</th>
            <th >
                刪除</th>
        </tr>
    </thead>
    <tbody id="uploadBody">
    </tbody>
    </table>
  <!--上傳檔案列表end-->    

posted on 2012-11-11 14:03 mbtq 閱讀(...) 評論(...) 編輯 收藏

轉載於:https://www.cnblogs.com/mbtq/archive/2012/11/11/2765101.html

相關文章