Upload Multiple Files at a time Under a Button Click using Asp.Net C# VB.Net

Most of our project we have to develop a module to upload file/files. Its a common scenario for all developers. In classic ASP it was tedious but in ASP.NET we found a nice control to upload/store a file into the web server. The new control in ASP.NET is capable to do everything except few limitations like filtering, selecting multiple files at a time etc. So in this article I want to describe every aspects like uploading different type of file(s) with effective filtering, Security etc.

Focaus Area:
1. Save a file into web server hard drive.
2. Giving proper permissions to upload files
3. Apply client side filtering before upload by javascript
4. Apply server side filtering
5. Upload multiple or more than one file at a time
6. Understanding file size limitations

Save a file into web server hard drive:
So start by adding a new page in your project. Add the FileUpload control into your page. Also a add a button to upload the selected file into web server. So the scenario is user have to to select a file first then press a button to save. HTML code will be:

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="cmdUpload" runat="server" Text="Upload" OnClick="cmdUpload_Click" />

C# Code:

protected void cmdUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
FileUpload1.SaveAs(Server.MapPath("FileArchieve")+"\\"+FileUpload1.FileName);
}

VB.Net Code:

Protected Sub cmdUpload_Click(sender As Object, e As EventArgs)
	If FileUpload1.HasFile Then
		FileUpload1.SaveAs((Server.MapPath("FileArchieve") & "\") + FileUpload1.FileName)
	End If
End Sub

Note: Before running the application you must create a folder in your root directory & named it FileArchieve. Otherwise you will get the bellow DirectoryNotFoundException: Could find a path of the file…. like:

DiretoryNotFoundException

The output interface like:
UI

Click on the browse button to select a file from your local PC then click on the Upload button. Hope now you can upload a file. If cant then check the permission section later in this post.

Giving proper permissions to upload files:
The code works in your development PC but you may receive an error when you publish your site. First check that you created a folder where you want to publish. Secondly check that this folder has enough permission to write a file into this directory.

To do that: First, right-click the folder on which you want to upload files. Then the properties dialog for the selected folder opens. Now click on Security tab to make sure that the ASP.NET Machine Account is included in the list and has the permission to write to the folder. Look at the security tab UI:

security tab

If you look at the image you will see that ASP.NET Machine Account absent here. Now i will let you know how we can add the ASP.NET Machine Account into the list. Click on the Add button under Security Tab. Write aspnet and click OK.

security tab2

After clicking OK set the write permission to this account. Hope everything will be OK. The final Figure should be:
security tab3

Note: One importatnt thing is if hosting server using Windows Server 2003, then the ASP.Net account name is IIS_WPG. In windows server 2008 it is IIS_IUSRS. So you need to allow appropriate permission (Read/Write) to this user on your server folder to upload the file.

Client side filtering:
If you are familiar with .net desktop application then you may search the functionality like Filter property of OpenFileDialog. For you, the answer is NOP. Asp.net has no functionality like OpenFileDialog. But we can make it using javascript. Check the below script and append it in your page:

    <script type="text/javascript">
        function CheckFileExtension() {
            var ctrlUpload = document.getElementById('<%=FileUpload1.ClientID%>');

            //Does the user browse or select a file or not
            if (ctrlUpload.value == '') {
                alert("Select a file first!");
                ctrlUpload.focus();
                return false;
            }

            //Extension List for validation. Add your required extension here with comma separator
            var extensionList = new Array(".BMP", ".JPG", ".GIF");
            //Get Selected file extension
            var extension = ctrlUpload.value.slice(ctrlUpload.value.indexOf(".")).toLowerCase();

            //Check file extension with your required extension list.
            for (var i = 0; i < extensionList.length; i++) {
                if (extensionList[i] == extension)
                    return true;
            }
            alert("You can only upload below File Type:\n\n" + extensionList.join("\n"));
            ctrlUpload.focus();
            return false;
        }
</script>

Now modify your cmdUpload HTML in the following way to invoke the script first:

<asp:Button ID="cmdUpload" runat="server" Text="Upload" OnClientClick="return CheckFileExtension();" OnClick="cmdUpload_Click" />

Script has been tested for the below Browsers:
1. IE
2. Mozilla Firefox
3. Opera
4. Google Chrome

Server side filtering:
Server side filtering is must since readers may off javascript functionality. To apply the server side validation you have to modify the cmdUpload button click event handler with the following code segment:

C# Code:

    protected void cmdUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string extension=System.IO.Path.GetExtension(FileUpload1.FileName).ToUpper();
                if (extension == ".BMP" || extension == ".JPG" || extension == ".GIF")
                FileUpload1.SaveAs(Server.MapPath("FileArchieve")+"\\"+FileUpload1.FileName);
            }
        }

VB.Net Code:

Protected Sub cmdUpload_Click(sender As Object, e As EventArgs)
	If FileUpload1.HasFile Then
		Dim extension As String = System.IO.Path.GetExtension(FileUpload1.FileName).ToUpper()
		If extension = ".BMP" OrElse extension = ".JPG" OrElse extension = ".GIF" Then
			FileUpload1.SaveAs((Server.MapPath("FileArchieve") & "\") + FileUpload1.FileName)
		End If
	End If
End Sub

Note: You can also check file exist or not by adding the below condition:
C# Code:

if (!System.IO.File.Exists(Server.MapPath("FileArchieve") + "\\" + FileUpload1.FileName))

VB.Net Code:

        If (Not System.IO.File.Exists(Server.MapPath("FileArchieve") + "\\" + FileUpload1.FileName)) Then
        End If

Upload multiple files with a single click:
No built-in capabilities in the Microsoft .NET Framework enable you to upload multiple files from a single ASP.NET page. The trick is to import the System.IO class into your ASP.NET page and then to use the HttpFileCollection class to capture all the files that are sent in with the Request object. This approach enables you to upload as many files as you want from a single page. To do this here i have added 5 FileUpload controls Like:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:FileUpload ID="FileUpload1" runat="server" /><br />
    <asp:FileUpload ID="FileUpload2" runat="server" /><br />
    <asp:FileUpload ID="FileUpload3" runat="server" /><br />
    <asp:FileUpload ID="FileUpload4" runat="server" /><br />
    <asp:FileUpload ID="FileUpload5" runat="server" /><br />
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</asp:Content>

Modify the button click event with the following code:
C# Code:

    protected void Button1_Click(object sender, EventArgs e)
    {
        HttpFileCollection uploadedFiles = Request.Files;
        for (int i = 0; i < uploadedFiles.Count; i++)
        {
            if (uploadedFiles[i].ContentLength > 0)
                uploadedFiles[i].SaveAs(Server.MapPath("FileArchieve") + "\\" + System.IO.Path.GetFileName(uploadedFiles[i].FileName));
        }
     }

VB.Net Code:

    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        Dim uploadedFiles As HttpFileCollection = Request.Files
        For i As Integer = 0 To uploadedFiles.Count - 1
            If uploadedFiles(i).ContentLength > 0 Then
                uploadedFiles(i).SaveAs(Server.MapPath("FileArchieve") & "\" & System.IO.Path.GetFileName(uploadedFiles(i).FileName))
            End If
        Next
    End Sub

Action Looks Like:
How to Upload Multiple Files at a time using Asp.Net Csharp VB.Net

Understanding file size limitations:
You may encounter an issue when you or your user wants to upload more than 4MB size file because the maximum size that can be uploaded to the server is 4MB or 4096kb by default, so that the size of the file to be uploaded should be less than or equal to 4 MB. To resolve this issue, you have to make some changes in the web.config file; e.g., if you want to upload around 10 MB each, then make the following change in the node of the system.web section of the web.config file.

<httpRuntime maxRequestLength="11000" executionTimeout="275"/>

You can do a lot with the httpRuntime section like idleTime, minFreeThreads, appRequestQueueLilit. But the above two properties were more important. Here i stated 11000 as the value of maxRequestLength since its in kb and executionTimeout value is in second.

Ref:
http://msdn.microsoft.com/en-us/library/aa479405.aspx

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*