Allowing Users to Upload Multiple Files at Oncehttp://www.dotnetjunkies.com/images/trans.gif
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 l