上传
Allowing Users to Upload Multiple Files at Once
Summary: This article demonstrates how to allow users to upload multiple files from thier computer (the client) to your server. Specifically, this article will demonstrate how to set up a page that has 5 HtmlInputFile controls (rendered as <INPUT TYPE='FILE'> ) where a user can choose 5 images to upload. Only .jpg and .gif extensions will be accepted on the server and each one will be saved to a different directory::so any image that has the extension .jpg will be saved to the jpgs direcory and .gif will be saved to the gifs directory and everything else isn't saved at all. Before we get into the code I want to quickly go over some things that may or may not be new to you. First, System.Web.HttpFileCollection: this class "Provides access to and organizes files uploaded by the client" - essentially, it contains a collection of HttpPostedFile classes and is access through the System.Web.HttpConext.Current.Response.Files property. The second thing used is some static methods of the System.IO.Path class: The GetFileName and GetExtension methods are used. The GetFileName method will retrieve the file name and file extension from a path. The GetExtension method does exactly what it sounds like it should do. It gets the file extension from a file. Let's take a look at the code. The first code listing is the WebForm code and the second is the WebForm's code behind file. Note: for this to work properly you will have to create two sub-directories (gifs, jpgs) 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> As usual the WebForm is pretty boiler plate. 5 HtmlInputFile objects and some buttons for submitting the form and reseting the form. When this page is rendered you'll receive something like the following: 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() {
//loop through the files uploaded
System.Web.HttpFileCollection _files = System.Web.HttpContext.Current.Request.Files;
//Message to the user
System.Text.StringBuilder _message = new System.Text.StringBuilder("Files Uploaded:<br>");
try
{
for ( System.Int32 _iFile = 0; _iFile < _files.Count; _iFile ++ )
{
// Check to make sure the uploaded file is a jpg or gif
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" )
{
//Save File to the proper directory
_postedFile.SaveAs(
System.Web.HttpContext.Current.Request.MapPath(
"gifs/") + _fileName);
_message.Append(_fileName + "<BR>");
}
else if ( _fileExtension == ".jpg" )
{
//Save File to the proper directory
_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!</font> <BR>");
}
}
Label1.Text = _message.ToString();
return true;
}
catch ( System.Exception Ex )
{
Label1.Text = Ex.Message ;
return false;
}
}
#endregion
#region Web Form Designer generated code
override protected void OnInit(System.EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
Well just be looking at the SaveImages method. The first thing that's done is a new HttpFileCollection object and a new StringBuilder object is created - the StringBuilder is used to create a message to the user. Then we loop through the HttpFileCollection object and verify whether a gif or jpeg was uploaded - if so it is saved to the proper directory and if not then nothing happens. Take a look at the following images. The first is the page right before it is posted to the server and the second is right after. Notice that there is both jpg, gif, and psd extensions being uploaded. Right Before Right After Notice that because the .psd file wasn't valid an error message was displayed to the user. Conclusion: When you want to enable users to upload multiple files use the HttpFileCollection to access the HttpPostedFile's uploaded.