在ASP.NET 4.0环境中使用c#进行多文件上载

pri*_*ine 10 html c# asp.net upload file

我正在寻找上传多个文件的解决方案(点击浏览按钮,然后使用shift键选择多个文件).

我看到需要通过单击"浏览"按钮逐个上传的几个解决方案,然后单击"提交"按钮.但我需要允许用户同时选择多个文件.

Dev*_*rke 5

<input type="file">在很大程度上锁定在Web浏览器出于安全考虑.它不允许多个文件选择.您需要使用Flash或Silverlight来执行此操作,或使用多个<input type="file">字段.

您可以允许用户选择一个文件,然后提供"添加另一个文件"按钮,该按钮使用jQuery生成另一个文件上载输入.您可以通过这种方式允许无限数量的上传,但用户必须单独浏览每个上传.

另外,HTML 5将支持多个文件上传,但在当前的Web浏览器中并没有广泛实现,因此不是一种选择.


Shr*_*eya 5

设置属性"AllowMultiple = true"如下所示.此属性适用于4.5框架.

 <asp:FileUpload ID="file_upload" runat="server" AllowMultiple="true" />
Run Code Online (Sandbox Code Playgroud)

这将允许您一次选择多个文件

Aspx代码:

<form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="file_upload" runat="server" AllowMultiple="true" />
        <asp:Button ID="btnFileUpload" runat="server" Text="Upload" OnClick="btnFileUpload_Click" />
        <asp:Label ID="lblUploadStatus" runat="server"></asp:Label>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

Aspx.cs代码:

protected void btnFileUpload_Click(object sender, EventArgs e)
{
    try
    {
        if (file_upload.HasFile && file_upload.PostedFiles.All(x => x.ContentType == "image/jpeg" && x.ContentLength < 102400))
        {
            foreach (var file in file_upload.PostedFiles)
            {
                file_upload.SaveAs(Server.MapPath("~/") + Path.GetFileName(file.FileName));
            }
            lblUploadStatus.Text = "File(s) uploaded successfully.";
        }
        else
        {
            lblUploadStatus.Text = "Please upload proper file.";
        }
    }
    catch (Exception ex)
    {
        lblUploadStatus.Text = "Error in uploading file." + ex.Message;
    }
}
Run Code Online (Sandbox Code Playgroud)


Dev*_*avi 5

我们一直在使用下面的jQuery插件来帮助我们.

jQuery多文件上传插件

在包含必要的js文件之后:jQuery.multifile.pack.js,我们可以像下面一样使用它.

<input type="file" id="flAttachment" runat="server" tabindex="8" class="multi max-3 accept-gif|jpg|xlsx|xls|doc|docx|pdf|png" size="37" />
Run Code Online (Sandbox Code Playgroud)

Giving class="multi"使它接受多个文件.

您也可以根据需要应用约束.就像class = "max-3"允许上传最多三个文件一样.class = "accept-gif|jpg"只允许上传带有gifOR jpg扩展名的文件.

要在服务器端获取多个文件,您需要包含namespace:System.Web;

然后,您可以使用以下代码迭代上传的每个文件.

if (Request.Files.Count > 0)
{
    HttpFileCollection attachments = Request.Files;
    for (int i = 0; i < attachments.Count; i++)
    {
        HttpPostedFile attachment = attachments[i];
        if (attachment.ContentLength > 0 && !String.IsNullOrEmpty(attachment.FileName))
        {
            //do your file saving or any related tasks here.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这与.net framework版本无关.