Allow users to upload multiple files at once

Source: Internet
Author: User
Tags file upload httpcontext reset save file
Upload allowing Users to Upload multiple Files at Once
Summary:This article demonstrates you to allow users to upload multiple files from thier computer (the client) to your server. Specifically, this article would demonstrate how to set up a page that has 5HtmlInputFile controls (rendered as <input type= ' FILE ' >Where a user can choose 5 images to upload. only. jpg and. gif extensions'll is accepted on the server and each one would be saved to a different directory::so any I Mage that has the extension. jpg is saved to the JPGs Direcory directory and saved Thing else isn ' t saved at all. Before we get into the code I want to quickly go over some things, or may, or May is new to you. A, System.Web.HttpFileCollection:This class "provides access to and organizes files uploaded by the client"-essentially, it contains a collection of HttppostedfileClasses and is access through the System.Web.HttpConext.Current.Response.FilesProperty. The second thing used is some static methods of the System.IO.PathClass:the GetFileNameand getextensionMethods are used. The GetFileNameMethod would retrieve the file name and file extension from path. The getextensionmethod 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 WebForm code and the second is the code behind file of the listing is the. Note:For it to work properly your'll have to create two sub-directories (GIFs, JPGs) upload.aspx<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" > <HTML>
<HEAD>
<title&gt::: UPLOAD SAMPLE::: </title>
</HEAD>
<body>
<center>
<form id= "UPLOAD" method= "POST" runat= "server" enctype= "Multipart/form-data" >
<P>
<input type= "File" runat= "server" size= "id=" File1 "Name=" ></P>
<P>
<input type= "File" runat= "server" size= "id=" File2 "Name=" ></P>
<P>
<input type= "File" runat= "server" size= "id=" File3 "Name=" ></P>
<P>
<input type= "File" runat= "server" size= "id=" File4 "Name=" ></P>
<P>
<input type= "File" runat= "server" size= "id=" File5 "Name=" ></P>
<p><strong&gt:: </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 HtmlInputFileObjects 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.csNamespace 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 the call are required by the ASP.net Web Form Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Required to Designer support-do not modify
The contents is with the Code Editor.
</summary>
private void InitializeComponent ()
{
This. Load + = new System.EventHandler (this. Page_Load);

}
#endregion
}
}
The very just is looking at the Saveimages method. The "thing" is a new httpfilecollectionObject and a new StringBuilderObject is Created-the StringBuilderis used to create a message to the user. Then we loop through the httpfilecollectionObject and verify whether a GIF or JPEG was uploaded-if so it are saved to the proper directory and if not then nothing h Appens. Take a look at the following images. The ' The ' is the ' page right ' before it is posted to the server and the second are right. Notice that there is both jpg, GIF, and PSD extensions being uploaded. Right before right afterNotice that because the. psd file wasn ' t valid a error message is displayed to the user. Conclusion:When you are want to enable users to upload multiple files with the httpfilecollectionTo access the Httppostedfile ' sUploaded.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.