asp.net动态多文件上传

时间:2016-11-02 04:39:07

标签: javascript c# jquery asp.net webforms

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < Request.Files.Count; i++)
        {
            HttpPostedFile PostedFile = Request.Files[i];
            if (PostedFile.ContentLength > 0)
            {
                string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
                PostedFile.SaveAs(Server.MapPath("Files\\") + FileName);
            }
        }
    }

<script type="text/javascript">
        var counter = 0;
        function AddFileUpload() {
            var div = document.createElement('DIV');
            div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +
                            '" type="file" />' +
                            '<input id="Button' + counter + '" type="button" ' +
                            'value="Remove" onclick = "RemoveFileUpload(this)" />';
            document.getElementById("FileUploadContainer").appendChild(div);
            counter++;
        }
        function RemoveFileUpload(div) {
            document.getElementById("FileUploadContainer").removeChild(div.parentNode);
        }
    </script>

上传功能可以动态添加用户想要的内容。

 <div>
            <span style="font-family: Arial">Click to add files</span>
    <input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
            <div id="FileUploadContainer">
            </div>
            <asp:Button ID="btnUpload" runat="server"
                Text="Upload" OnClick="btnUpload_Click" />

        </div>

我现在面临的问题是当我点击上传时  for (int i = 0; i < Request.Files.Count; i++)这一行Request.Files.Count always = 0,即使我有一个或多个要上传的文件。我也试图调试此Request.Files.Count 0 ..

2 个答案:

答案 0 :(得分:1)

只需将FileUploadContainer div和Upload Button包裹在form中,并将其方法设置为POST。现在您应该在Request.Files.Count下获取文件。只是下面的一个示例

<div>
    <span style="font-family: Arial">Click to add files</span>
    <input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
    <form id="frmUploads" runat="server" method="POST">
        <div id="FileUploadContainer">
        </div>
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </form>
</div>

答案 1 :(得分:1)

运行您的页面,查看源代码并确保文件上传按钮和容器div包含在表单元素中,如果没有,则使用以下表单元素声明将它们包围起来

<form method='POST' enctype='multipart/form-data'>

<div>
<!-- REST of your HTML --!>

            <span style="font-family: Arial">Click to add files</span>
    <input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
            <div id="FileUploadContainer">
            </div>
            <asp:Button ID="btnUpload" runat="server"
                Text="Upload" OnClick="btnUpload_Click" />

        </div>

</form>