Multiple Files Upload in ASP.NET and ASP.NET with jQuery

SheoNarayan
Posted by in ASP.NET category on for Intermediate level | Views : 71085 red flag
Rating: 4.75 out of 5  
 4 vote(s)

This article shows how to upload single and multiple files using FileUpload control on the server using ASP.NET and ASP.NET + jQuery plug in. This articles also covers related configuration settings you need to set in order to limit the size and type of file to be uploaded.


 Download source code for Multiple Files Upload in ASP.NET and ASP.NET with jQuery

Introduction

FileUpload control is a frequently used control when working with ASP.NET Applications. In this article, I have shown how to upload Single as well as Multiple files on the server in ASP.NET and also with ASP.NET and jQuery plug in. jQuery FileUpload plug-in can be downloaded from fyneworks.com website (http://www.fyneworks.com/jquery/multiple-file-upload)

Picture 1

Video of this article

 You can watch the video of this article at http://www.dotnetfunda.com/tutorials/videos/x76-multiple-files-upload-in-aspnet-and-aspnet-with-jquery-.aspx

Prerequisite

In order to understand this article, you should be familiar with ASP.NET and jQuery. You should have the jQuery file and along with that you should download the jQuery MultiFile plug in from fyneworks.com website (http://www.fyneworks.com/jquery/multiple-file-upload).

Create an aspx page

Lets create as aspx page as displayed in the above picture. Below code snippet is the part of the head in my aspx page.

<head runat="server">

<title>Multiple File Upload in ASP.NET</title>

<style type="text/css">

body

{

font-family: Arial;

font-size: 10pt;

}

th

{

background-color: #efefef;

}

</style>

<script src="../jquery-1.4.min.js" type="text/javascript"></script>

<script src="../jquery.MultiFile.pack.js" type="text/javascript"></script>

</head>

The body of the aspx page looks like below. In this, I have created a table with 4 cells as displayed in the picture above and placed FileUpload control as per our need. As I am going to cover single and multiple FileUpload in the same article so I have designed the page in such a way that it can upload single as well as multiple files on respective button clicks.

Notice that I have referenced both jQuery and jQuery multi file plug .js files. These files are mandatory to work with ASP.NET + jQuery forms (last 2 forms).

<form id="form1" name="form1" runat="server">

<div>

<table width="600" cellpadding="4" cellspacing="2" border="1">

<tr>

<th colspan="2">

Single/Multiple File upload using ASP.NET

</th>

</tr>

<tr valign="top">

<td>

Single File Upload

<br />

<asp:FileUpload ID="FileUploadSingle" runat="server" />

<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="PlainUploadFile" />

</td>

<td>

Multiple File Upload

<br />

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:FileUpload ID="FileUpload2" runat="server" />

<asp:FileUpload ID="FileUpload3" runat="server" />

<asp:FileUpload ID="FileUpload4" runat="server" />

<div style="text-align: right;">

<a id="linkMore" href="javascript:void(0)" onclick="javascript:ShowHideFileUpload(this.id)">

+ Add More ...</a></div>

<div style="display: none;" id="divShowMore">

<asp:FileUpload ID="FileUpload5" runat="server" />

<asp:FileUpload ID="FileUpload6" runat="server" />

<asp:FileUpload ID="FileUpload7" runat="server" />

<asp:FileUpload ID="FileUpload8" runat="server" />

</div>

<asp:Button ID="btnSub" runat="server" Text="Submit" OnClick="PlainUploadFiles" /><br /><br />

</td>

</tr>

<tr>

<th colspan="2">

Single/Multiple File upload using ASP.NET + jQuery

</th>

</tr>

<tr valign="top">

<td>

jQuery Single File Upload<br />

<asp:FileUpload ID="FileUpload9" runat="server"/>

<asp:Button ID="Button2" runat="server" Text="Submit" OnClick="jQueryUploadFile" />

</td>

<td>

jQuery Multiple File Upload with .jpg and .gif only<br />

<asp:FileUpload ID="FileUpload10" runat="server" class="multi" accept="png|jpg" />

<asp:Button ID="Button3" runat="server" Text="Submit" OnClick="jQueryUploadFiles" />

</td>

</tr>

</table>

<br />

<asp:Label ID="lblMessage" runat="server" EnableViewState="false" ForeColor="Green" />

<br />

<asp:Label ID="lblError" runat="server" EnableViewState="false" ForeColor="Red" />

</div>

</form>

<script language="javascript" type="text/javascript">

// show more file upload

function ShowHideFileUpload(id) {

document.getElementById('divShowMore').style.display = '';

document.getElementById(id).style.display = 'none';

}

</script>

You can notice that the 2nd form has 4 FileUpload controls and a + Add More ... link, when this link is clicked it fires ShowHideFileUpload javascript function that hides the link and shows rest 4 FileUpload controls (rest 4 FileUpload controls has been kept in hidden div that is shown on link click).

In the "Single/Multiple File upload using ASP.NET + jQuery" section, notice the FileUpload control class attribute value. You will notice that its value is "multi", this is mandatory for the jQuery.MultiFile plug in to work, otherwise the jQuery plug in will not be applied for that control.

You might have noticed one more attribute called accept that let us specify the file type we want to accept to be uploaded. The extension of the file can be specified separated by "|" sign. In my case I have specified "png|jpg", so that FileUpload control shall only accept .png or .jpg files to be uploaded (as displayed in the above picture).

In the above code snippet, you may notice that I have kept two Label controls that I shall use to write the success or failure messages.

Picture 2

Code to Single / Multiple file upload in ASP.NET, ASP.NET + jQuery


As you can see in Picture 2, that I have 4 buttons so I have 4 code behind events that fires on click event of those buttons. Those 4 methods looks like below

/// <summary>

/// upload single file in asp.net

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void PlainUploadFile(object sender, EventArgs e)

{

UploadFileUsingASPNET(FileUploadSingle);

}

 

/// <summary>

/// upload multiple files using asp.net

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void PlainUploadFiles(object sender, EventArgs e)

{

try

{

/*

UploadFileUsingASPNET(FileUpload1);

UploadFileUsingASPNET(FileUpload2);

UploadFileUsingASPNET(FileUpload3);

UploadFileUsingASPNET(FileUpload4);

UploadFileUsingASPNET(FileUpload5);

UploadFileUsingASPNET(FileUpload6);

UploadFileUsingASPNET(FileUpload7);

UploadFileUsingASPNET(FileUpload8);

*/

// here we know that we have 8 FileUpload controls from FileUpload1 to FileUpload8

// so we shall loop 8 times and retrieve each control one by one

FileUploadUsingJQuerySelectionMethod();

}

catch (Exception ee)

{

lblError.Text = ee.Message;

}

}

 

/// <summary>

/// Single file upload using ASP.NET using jQuery file selection mechanism

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void jQueryUploadFile(object sender, EventArgs e)

{

FileUploadUsingJQuerySelectionMethod();

}

 

/// <summary>

/// Multiple file upload using ASP.NET using jQuery file selection mechanism

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void jQueryUploadFiles(object sender, EventArgs e)

{

FileUploadUsingJQuerySelectionMethod();

}

Code Listing  - 1

Single FileUpload in ASP.NET

You can notice that in the first method (PlainUploadFile method in above code snippet fires when first button is clicked on the page.), I am calling another private method called UploadFileUsingASPNET(FileUploadSingle)that is actually doing all my work (eg. validating the file type and uploading it to the server).

/// <summary>

/// file upload file using ASP.NET FileUpload control

/// </summary>

/// <param name="fileUpload"></param>

private void UploadFileUsingASPNET(FileUpload fileUpload)

{

try

{

// check if file has been selected

if (fileUpload.HasFile)

{

string path = Server.MapPath("~/MultipFileUpload/");

string fileName = Path.GetFileName(fileUpload.PostedFile.FileName);

// check for the valid file extension

string fileExtension = Path.GetExtension(fileName).ToLower();

if (fileExtension.Equals(".gif") || fileExtension.Equals(".jpg"))

{

// now save the file to the disk

fileUpload.SaveAs(path + fileName);

lblMessage.Text += "File : <b>" + fileName + "</b> uploaded successfully ! <br />";

}

else

{

lblError.Text = "Only .gif and .jpg files are allowed.";

}

}

else

{

lblError.Text = "Please select a valid file.";

}

}

catch (Exception ee)

{

lblError.Text = ee.Message;

}

}

In this method, I am passing the control that selects the file as parameter, in my case its name is FileUploadSingle. In first line after try block I am trying to validate if user has selected any file and then getting the path to be uploaded and retrieving the name of the file. Then checking if the user has selected valid file name. If all these conditions are passed then I am using FileUpload.SaveAs method and passing the path where my file needs to be uploaded.

Multiple File Upload in ASP.NET

When the 2nd button is clicked, the PlainUploadFiles method is called. We can upload multiple methods in two ways that I have shown here.

First way of uploading multiple files in ASP.NET

Call the UploadFileUsingASPNET(FileUploadSingle) method (shown above ) multiple times and pass different FileUpload controls every time. In my case, I know that I have placed 8 FileUpload controls in the 2nd form so I have called it 8 times. In my code snippet above, I have commented this code and have called another private method caleld FileUploadUsingJQuerySelectionMethod (described below) that does the work for us.

Second way of uploading multiple files in ASP.NET

In this way, get the collection of all FileUpload controls on the page and loop through each one of them. Get the each FileUpload control one by one in the loop and check if it has some file selction and save the file on the server.

Note that in this method, we can't use foreach loop as HttpFileCollection gives the name of the control (id) rather than the HttpPostedFile object in the HttpFileCollection.

/// <summary>

/// file upload using jQuery file selection mechanism

/// </summary>

private void FileUploadUsingJQuerySelectionMethod()

{

// check if file has been selected

HttpFileCollection files = Request.Files;

for (int i = 0; i < files.Count; i++)

{

HttpPostedFile file = files[i];

if (file.ContentLength > 0)

{

string path = Server.MapPath("~/MultipFileUpload/");

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

// now save the file to the disk

file.SaveAs(path + fileName);

lblMessage.Text += "File : <b>" + fileName + "</b> uploaded successfully !<br />";

}

}

}

Uploading a single File in ASP.NET and jQuery

This is simple, notice the 3rd method from Code Listing 1, I have simply called FileUploadUsingJQuerySelectionMethod method explained above. Despite that it will loop through each FileUpload control placed on the page, it will work for us as we are going to select file from one FileUpload control.

Uploading Multiple Files in ASP.NET and JQuery

This is simple too, notice the 4th method from Code Listing 1, I have simply called FileUploadUsingJQuerySelectionMethod method explained above again. Despite that it will loop through each FileUpload controls placed on the page, whatever control will have the File selection will be processed and files will be uploaded on the server.

Web.Config setting

In order to limit the size of the file to be uploaded, we can set the maxReqestLength attribute of the httpRuntime node in web.config file. The file size is set in the KB, so in my case I have limited the file to be uploaded size to  200  KB only.

<system.web>

<httpRuntime maxRequestLength="200" />

</system.web>

How to work with database when uploading File on the server

Generally, when we upload the file on the server, we just save the name of the file along with path in the database and save the actual file on the server in file system (hard disk). At the time of listing we use html <img src="path" /> control and specify the path from the database that shows the image from the file system. Notice that the path should be stored in the database from the root in order to avoid confusion while showing the image.

Saving the entire image in the database is generally not recommended as generally images sizes are large in compared to text and it takes a lot of space in the database and make the database bulky. However, in certain scenario, it is done. Hopefully this article shall help you in that case http:// www. beansoftware.com/ASP.NET-Tutorials/ Save-Read-Image-Database.aspx (I have not used this personally).

Conclusion

Uploading single or multiple files on the server in ASP.NET looks tough but its not, FileUpload control is easy to use and if you have refactored your properly, its matter of few lines. jQuery MultipFile plug in from fyneworks. com comes with a boon to provide sleek look and feel to the user and also avoids chance of wrong file selection at the client side itself.

There are already couple of articles written on FileUpload control on this website, you may go ahead and read them as well, despite all articles uses on FileUpload control, their presentation is different and hope you will them all.

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Poster on: 8/9/2010
Very Good, you have covered everything that is needed for FileUpload control. Keep writing.
Posted by: Prabhakar on: 4/29/2011 | Points: 25
Hi Sheo Narayan

gud article . . it's a very useful for working on image's
Posted by: Thiru on: 12/9/2011 | Points: 25
Hi Sheo Narayan,
Very good article.
I like to allow image size upto 800px (width) and 600px (height)
how to do the same here ?

Login to post response

Comment using Facebook(Author doesn't get notification)