下面我将为大家讲解如何同时上传多个文件
我们在页面中添加5个<input type=file>上传的类型只限定在.gif和.jpg两种,并根据不同的类型放入不同的文件夹中。
我先给出upload.aspx源代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML>
<HEAD>
<title>::: UPLOAD SAMPLE ::: </title>
</HEAD>
<body>
<center>
<form id="UPLOAD" method="post" runat="server" enctype="multipart/form-data">
<h3>Multiple File Upload Example</h3>
<P>
<INPUT type="file" runat="server" size="50" ID="File1" NAME="File1"></P>
<P>
<INPUT type="file" runat="server" size="50" ID="File2" NAME="File2"></P>
<P>
<INPUT type="file" runat="server" size="50" ID="File3" NAME="File3"></P>
<P>
<INPUT type="file" runat="server" size="50" ID="File4" NAME="File4"></P>
<P>
<INPUT type="file" runat="server" size="50" ID="File5" NAME="File5"></P>
<P><STRONG>:: </STRONG>
<asp:LinkButton id="LinkButton1" runat="server" Font-Names="Verdana" Font-Bold="True" Font-Size="XX-Small">Upload Images</asp:LinkButton> <STRONG>::
</STRONG> <A href="JavaScript:document.forms[0].reset()" id="LinkButton2" style="FONT-WEIGHT:bold;FONT-SIZE:xx-small;FONT-FAMILY:verdana">
Reset Form</A> <STRONG>::</STRONG></P>
<P>
<asp:Label id="Label1" runat="server" Font-Names="verdana" Font-Bold="True" Font-Size="XX-Small" Width="400px" BorderStyle="None" BorderColor="White"></asp:Label></P>
<P> </P>
</form>
</center>
</body>
</HTML>
Update.aspx.cs 源代码
namespace HowTos.MultipleImageUpdate
{
public class UPLOAD : System.Web.UI.Page
{
#region User Defined Code
protected System.Web.UI.WebControls.LinkButton LinkButton1;
protected System.Web.UI.WebControls.Label Label1;
private void Page_Load(System.Object sender, System.EventArgs e)
{
if ( this.IsPostBack )
this.SaveImages();
}
private System.Boolean SaveImages() {
//文件上传时循环执行
System.Web.HttpFileCollection _files = System.Web.HttpContext.Current.Request.Files;
//发送给浏览器的信息
System.Text.StringBuilder _message = new System.Text.StringBuilder("Files Uploaded:<br>");
try
{
for ( System.Int32 _iFile = 0; _iFile < _files.Count; _iFile ++ )
{
// 检查上传文件是否为gif或jpg
System.Web.HttpPostedFile _postedFile = _files[_iFile];
System.String _fileName, _fileExtension;
_fileName = System.IO.Path.GetFileName(
_postedFile.FileName);
_fileExtension = System.IO.Path.GetExtension(
_fileName);
if ( _fileExtension == ".gif" )
{
//保存文件到指定文件夹
_postedFile.SaveAs(
System.Web.HttpContext.Current.Request.MapPath(
"gifs/") + _fileName);
_message.Append(_fileName + "<BR>");
}
else if ( _fileExtension == ".jpg" )
{
//保存文件到指定文件夹
_postedFile.SaveAs(
System.Web.HttpContext.Current.Request.MapPath(
"jpgs/") + _fileName);
_message.Append(_fileName + "<BR>");
}
else {
_message.Append(_fileName + " <font color=\"red\">failed!! Only .gif and .jpg images allowed