个性化阅读
专注于IT技术分析

asp.net上传多个文件

本文概述

ASP.NET FileUpload控件提供AllowMultiple属性,以将多个文件上传到服务器。此属性为true或false。

<asp:FileUpload>标记用于创建一个浏览按钮,使我们可以上传文件。让我们创建一个上传多个文件的示例。

ASP.NET上载多个文件的示例

本示例包含以下文件。

// UploadMultipleFilesExample.aspx

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="UploadMultipleFilesExample.aspx.cs" Inherits="UploadMultipleExample.UploadMultipleFilesExample" %>
<!DOCTYPE html>  
    <html xmlns="http://www.w3.org/1999/xhtml">  
    <head runat="server">  
        <title></title>  
    </head>  
    <body>  
        <form id="form1" runat="server">  
            <div>  
                <h3>Upload Multiple Files</h3>  
                <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />  
            </div>  
            <p>  
                <asp:Button ID="Button1" runat="server" Text="Upload File" OnClick="Button1_Click" />  
            </p>  
        </form>  
        <p>  
            <asp:Label runat="server" ID="FileUploadStatus"></asp:Label>  
        </p>  
    </body>  
    </html>

// UploadMultipleFilesExample.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace UploadMultipleExample
{
    public partial class UploadMultipleFilesExample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
            {
                var count = 0;
                foreach (HttpPostedFile uploadedFile in FileUpload1.PostedFiles)
                {
                    string fn = System.IO.Path.GetFileName(uploadedFile.FileName);
                    string SaveLocation = Server.MapPath("upload") + "\\" + fn;
                    try
                    {
                        uploadedFile.SaveAs(SaveLocation);
                        count++;
                    }
                    catch (Exception ex)
                    {
                        FileUploadStatus.Text = "Error: " + ex.Message;
                    }
                }
                if (count > 0)
                {
                    FileUploadStatus.Text = count + " files has been uploaded.";
                }
            }
            else
            {
                FileUploadStatus.Text = "Please select a file to upload.";
            }
        }
    }
}

输出:

选择2个文件上传

最初,看到上传文件夹为空。

将文件上传到服务器。

现在,查看上传文件夹。它包含上传的两个文件。

赞(0)
未经允许不得转载:srcmini » asp.net上传多个文件

评论 抢沙发

评论前必须登录!