多文件上传的方法其实很简单,在页面上添加多个html文件上传控件,就可在代码中用如下语句System.Web.HttpContext.Current.Request.Files来取得页面中的所有文件上传控年对象,然后调用 Files对象的SaveAs就可将多个文件上传上去,跟单文件上传没有多大区别。
【全文】
如下代码示例,可将多个文件上传到服务器,并显示在表格中和列表框中,并可将列表框中选择的文件从服务器删除掉。
[页面文件HTML]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script language="JavaScript">
function addFile()
{
//添加文件上传Html组件
var str ='<input type="file" name="File" class="FileUpStyle" /><br>'
document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
}
function Button1_onclick() {
//重置文件上传Html组件
var str='<input type="file" name="File"class="FileUpStyle" id="File1" /> ';
str=str+'<br>';
document.getElementById('MyFile').innerHTML=str;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>多文件上传示例</title>
<STYLE TYPE="text/css" MEDIA=screen>
<!--
.FileUpStyle {
font-size: 12px;
font-weight: lighter;
font-variant: normal;
border: 1px solid #006699;
width: 250px;
}
-->
</STYLE>
</head>
<body style="font-size: 9pt; color: #000066;">
<form id="form1" runat="server" enctype="multipart/form-data">
多文件上传示例<br />
<input type="button" value="增加" onclick="addFile()" style="border-right: #6699cc 1px solid; border-top: #6699cc 1px solid; font-size: 9pt; border-left: #6699cc 1px solid; width: 60px; border-bottom: #6699cc 1px solid">
<input type="button" value="重置" style="border-right: #6699cc 1px solid; border-top: #6699cc 1px solid; font-size: 9pt; border-left: #6699cc 1px solid; width: 60px; border-bottom: #6699cc 1px solid; height: 20px" id="Button1" language="javascript" onclick="return Button1_onclick()">
<asp:Button Runat="server" Text="上传" ID="Upload" OnClick="Upload_Click1" BorderColor="Desktop" BorderWidth="1px" Height="20px" Width="60px" ></asp:Button>
<asp:Button ID="btn_Refresh" runat="server" BorderColor="Desktop" BorderWidth="1px" Height="20px"
Text="刷新目录" Width="60px" OnClick="btn_Refresh_Click" /><br />
<div id="MyFile">
<input name="File" type="file" class="FileUpStyle" id="File1"/>
<br />
</div>
已上传的文件:<asp:LinkButton ID="btn_del" runat="server" OnClick="btn_del_Click" OnClientClick="return confirm('确认要网站上删除此文件吗?')">删除选择的文件</asp:LinkButton><br />
<asp:DropDownList ID="drp1" runat="server" Width="250px">
</asp:DropDownList>
<asp:Table ID="tableDirInfo" runat="server" ForeColor="#000040">
</asp:Table>
</form>
</body>
</html>
[程序代码文件CODE]
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Upload_Click1(object sender, EventArgs e)
{
HttpFileCollection _files = System.Web.HttpContext.Current.Request.Files;
for (int i = 0; i < _files.Count; i++)
{
string ShortFileName=_files[i].FileName.Substring(_files[i].FileName.LastIndexOf("\\")+1);
if (ShortFileName != "")
{
_files[i].SaveAs(Server.MapPath("~/Files/" + ShortFileName));
//Page.Response.Write("文件名:[" + ShortFileName + "]上传成功!<br>");
}
}
}
private void ShowFileList()
{
string strCurDir, FileName, FileExt;
//文件大小
long FileSize;
//最后修改时间;
DateTime FileModify;
//初始化时,默认为当前页面所在的目录
strCurDir = Server.MapPath("Files");
FileInfo fi;
DirectoryInfo dir;
TableCell td;
TableRow tr;
tr = new TableRow();
//动态添加单元格内容
td = new TableCell();
td.Controls.Add(new LiteralControl("文件名"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl("文件类型"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl("文件大小"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl("最后修改时间"));
tr.Cells.Add(td);
tableDirInfo.Rows.Add(tr);
//针对当前目录建立目录引用对象
DirectoryInfo dirInfo = new DirectoryInfo(strCurDir);
//清除Table中所有行
for (int j = 0; j < tableDirInfo.Rows.Count; j++)
tableDirInfo.Rows.RemoveAt(j);
drp1.Items.Clear();
//循环判断当前目录下的文件和目录
foreach (FileSystemInfo fsi in dirInfo.GetFileSystemInfos())
{
FileName = "";
FileExt = "";
FileSize = 0;
//如果是文件
if (fsi is FileInfo)
{
fi = (FileInfo)fsi;
//取得文件名
FileName = fi.Name;
drp1.Items.Add(FileName);
//取得文件的扩展名
FileExt = fi.Extension;
//取得文件的大小
FileSize = fi.Length;
//取得文件的最后修改时间
FileModify = fi.LastWriteTime;
}
else//否则是目录
{
dir = (DirectoryInfo)fsi;
//取得目录名
FileName = dir.Name;
//取得目录的最后修改时间
FileModify = dir.LastWriteTime;
//设置文件的扩展名为"文件夹"
FileExt = "文件夹";
}
//动态添加表格内容
tr = new TableRow();
td = new TableCell();
td.Controls.Add(new LiteralControl(FileName));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl(FileExt));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl(FileSize.ToString() + "字节"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl(FileModify.ToString("yyyy-mm-dd hh:mm:ss")));
tr.Cells.Add(td);
tableDirInfo.Rows.Add(tr);
}
}
protected void btn_Refresh_Click(object sender, EventArgs e)
{
//刷新目录列表
ShowFileList();
}
protected void btn_del_Click(object sender, EventArgs e)
{
//删除选择的文件
if (drp1.Items.Count != 0)
{
System.IO.File.Delete(Server.MapPath("Files/" + drp1.SelectedItem.Text));
ShowFileList();
}
}
}
方法二
在以前的Web应用中,上传文件是个很麻烦的事,现在有了.NET,文件上传变得轻而易举。下面的这个例子实现了多文件上传功能。可以动态添加输入表单,上传的文件数量没有限制。代码如下:
UpLoad.aspx
<%@ Page language="c#" Codebehind="UpLoad.aspx.cs" AutoEventWireup="false" Inherits="WebPortal.Upload" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>多文件上传</title>
<script language="JavaScript">
function addFile()
{
var str = '<INPUT type="file" size="50" NAME="File">'
document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
}
</script>
</HEAD>
<body>
<form id="form1" method="post" runat="server" enctype="multipart/form-data">
<div align="center">
<h3>多文件上传</h3>
<P id="MyFile"><INPUT type="file" size="50" NAME="File"></P>
<P>
<input type="button" value="增加(Add)" onclick="addFile()">
<input onclick="this.form.reset()" type="button" value="重置(ReSet)">
<asp:Button Runat="server" Text="开始上传" ID="UploadButton"></asp:Button>
</P>
<P>
<asp:Label id="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt"
Width="500px" BorderStyle="None" BorderColor="White"></asp:Label>
</P>
</div>
</form>
</body>
</HTML>
UpLoad.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebPortal
{
/// <summary>
/// UpLoad 的摘要说明。
/// 实现多文件上传
/// </summary>
public class Upload : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button UploadButton;
protected System.Web.UI.WebControls.Label strStatus;
private void Page_Load(object sender, System.EventArgs e)
{
/// 在此处放置用户代码以初始化页面
if (this.IsPostBack) this.SaveImages();
}
private Boolean SaveImages()
{
///'遍历File表单元素
HttpFileCollection files = HttpContext.Current.Request.Files;
/// '状态信息
System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
strMsg.Append("上传的文件分别是:<hr color=red>");
try
{
for(int iFile = 0; iFile < files.Count; iFile++)
{
///'检查文件扩展名字
HttpPostedFile postedFile = files[iFile];
string fileName, fileExtension;
fileName = System.IO.Path.GetFileName(postedFile.FileName);
if (fileName != "")
{
fileExtension = System.IO.Path.GetExtension(fileName);
strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>");
strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br>");
strMsg.Append("上传文件的文件名:" + fileName + "<br>");
strMsg.Append("上传文件的扩展名:" + fileExtension + "<br><hr>");
///'可根据扩展名字的不同保存到不同的文件夹
///注意:可能要修改你的文件夹的匿名写入权限。
postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + fileName);
}
}
strStatus.Text = strMsg.ToString();
return true;
}
catch(System.Exception Ex)
{
strStatus.Text = Ex.Message;
return false;
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.ID = "Upload";
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}