在ASP.NET 2.0中,用户可以通过FileUpload控件将本地的文件通过Web页面上传至服务器上,FileUpload控件由一个文本框和一个浏览按钮组成,点击“浏览”按钮允许用户选择一个本地的文件,并将文件由客户端上传到服务器。通过调用FileUpload控件的SaveAs方法将文件保存到服务器上的指定路径,这使得单个文件的上传变得容易。但是多个文件该如何实现呢?这篇POST将介绍在ASP.NET 2.0中使用HttpFileCollection类实现多文件的上传。
按照下更两个步骤:
第一步:在Web页面上放置需要数量的FileUpload控件,本例将放置3个。
第二步:添加一个Button控件,并命名为“上传”。
aspx 页面代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebUI._Default" %>
<!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 runat="server">
<title>ASP.NET 2.0多文件上传</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:FileUpload ID="FileUpload2" runat="server" />
<br />
<br />
<asp:FileUpload ID="FileUpload3" runat="server" />
<br />
<br />
<asp:Button ID="btnUpload" runat="server" Text="上 传"
onclick="btnUpload_Click" />
</div>
</form>
</body>
</html>
aspx.cs代码:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
namespace WebUI
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath("Upload") + "\\" + Path.GetFileName(hpf.FileName));
}
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
}
写在后面:
1、如果你每次上传的文件总大小超过了4MB,需要修改Web.config文件,在<httpRuntime>节点中设置maxRequestLength属性的值,单位为KB。
2、要给服务器上接收上传文件的目录赋予能写文件的权限,本例为Upload目录。
关于httpRuntime部分的更详细设置,大家可以至Google中搜索“httpRuntime”获得更多信息。
运行效果图
Demo下载:ASP.Net 2.0多文件上传Demo下载