Powered by Blogger.

Sunday, February 16, 2014

Upload multiple files in Asp.Net file upload control

In this post we will discuss how we can upload multiple files in Asp.Net file upload control.

Also you can check out my previous posts:

- Data files and Log files in sql server 2008

- Forms Authentication in Asp.Net

- What are different types of results in MVC?

To upload multiple photos using File Upload control we need to add  multiple="true" attribute to the file upload control.

Even if the property did not come in visual studio intellisense, you write this property it will not give any error. (For me it did not give any error so hoping it will not give any error for you also)

Below is the full code:

            <asp:FileUpload ID="FileUpload1" runat="server" multiple="true" Width="330px" /><br />
            <asp:Button ID="btnUpload" runat="server" Text="Click to Upload" OnClick="btnUpload_Click" />

.CS code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    protected void btnUpload_Click(object sender, EventArgs e)
        HttpFileCollection fileCollection = Request.Files;
        for (int i = 0; i < fileCollection.Count; i++)
            HttpPostedFile uploadfile = fileCollection[i];

            string fileName = Path.GetFileName(uploadfile.FileName);

            if (uploadfile.ContentLength > 0)
                uploadfile.SaveAs(Server.MapPath("~/Photos/") + fileName);              

Here if you want to validate image file extensions, then you can follow this article.

Check the fig below, when you will select multiple files it usually selects like below:

Once you upload the images will be shown.