Uploading Multiple Files in ASP.NET 2.0

Posted by: Suprotim Agarwal , on 8/1/2007, in Category ASP.NET
Views: 280687
Abstract: In earlier versions of ASP.NET, you could use the HTML FileUpload control to upload files. However there were a couple of efforts required by the developer to do so. ASP.NET 2.0 introduces the FileUpload server control that makes the implementation smoother. In this article, we will first explore how to upload a file using the FileUpload control and then extend the functionality to upload multiple files.
Uploading Multiple Files in ASP.NET 2.0
In ASP.NET 2.0, the FileUpload control enables users to upload file from your web pages. The FileUpload control consists of a text box and a browse button. Clicking on the button allow users to select a file on the client and upload it to the server. Let us first start off by exploring how to upload a single file in asp.net. To do so, follow these steps:
Step 1: Drag and drop the FileUpload server control from the toolbox. The code behind looks as follows :
<asp:FileUpload id=”FileUpload1” runat=”server” />
Step 2: Drop a Button control and rename it to “Upload”
<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” />
Step 3: Double click the Upload Button to add an event hander to the code behind.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
 
}
VB.NET

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)

End Sub

 
Step 4: Add the following code to the event handler
C#
 
protected void btnUpload_Click(object sender, EventArgs e)
{
        try
        {
            if (FileUpload1.HasFile)
            {
                FileUpload1.SaveAs(Server.MapPath("MyFiles") +
                    "\\" + FileUpload1.FileName);
            }
        }
        catch (Exception ex)
        {
            // Handle your exception here
        }
 
}
VB.NET

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)

Try

 

If FileUpload1.HasFile Then

FileUpload1.SaveAs(Server.MapPath("MyFiles") & "\" & FileUpload1.FileName)

End If

Catch ex As Exception

' Handle your exception here

 

End Try

End Sub

The “HasFile” property of our FileUpload control helps us to determine if a file has actually been uploaded. We then use the "SaveAs" method to save the file to disk.
That is all you require to implement the FileUpload functionality in your web pages. In order to retrieve the metadata information of the file being uploaded, you can drop a Label control on to the form designer and use the PostedFile.FileName and PostedFile.ContentLength on the FileUpload control. This would give you the uploaded file’s name and size respectively. Eg:
Label1.Text = FileUpload1.PostedFile.FileName;
Label1.Text += FileUpload1.PostedFile.ContentLength;
Uploading Multiple Files
 
So far so good. Let’s extend the above sample to upload multiple files at a time. Follow these steps mentioned below to do so: 
Step 1: Drag and drop multiple (in our case four) FileUpload controls on to the designer.
Step 2: Drop a Button control and rename it to “Upload”
<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” />
Step 3: Double click the Upload Button to add an event hander to the code behind.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
 
}
 
VB.NET

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)

End Sub

Step 4: Import the System.IO namespace.
using System.IO; - C#

Imports System.IO - VB.NET

Step 5: Use the ‘HttpFileCollection’ class to retrieve all the files that are uploaded. Files are encoded and transmitted in the content body using multipart MIME format with an HTTP Content-Type header. ASP.NET extracts this information from the content body into individual members of an HttpFileCollection.
The code would look as follows:
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
        try
        {
            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];              
                if (hpf.ContentLength > 0)
                {
                    hpf.SaveAs(Server.MapPath("MyFiles") + "\\" +
                      Path.GetFileName(hpf.FileName));                      
                }              
            }   
        }
        catch (Exception ex)
        {
            // Handle your exception here
        }
 
}
VB.NET

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)

Try

 

' Get the HttpFileCollection

Dim hfc As HttpFileCollection = Request.Files

For i As Integer = 0 To hfc.Count - 1

Dim hpf As HttpPostedFile = hfc(i)

If hpf.ContentLength > 0 Then

 

 

 

hpf.SaveAs(Server.MapPath("MyFiles") & "\" & Path.GetFileName(hpf.FileName))

End If

Next i

Catch ex As Exception

' Handle your exception here

 

 

End Try

End Sub

The ‘HttpPostedFile’ class provides methods and properties to access the contents and properties of each file. In our case, we use this class to check the length of the file. To retrieve the filename and length of the file uploaded, we can use hpf.FileName and hpf.ContentLength respectively.
Well, that was simple to implement, wasn’t it! However there are a few points to be kept in mind.
Some important points to consider while uploading
 
1.    To save a file to the server, the account associated with ASP.NET must have sufficient permissions on the folder, where the files are being uploaded. This would usually be the ‘ASPNET’ account for Windows XP or a similar OS. In Windows Server 2003, the account used is ‘NETWORKSERVICE’. So you would be required to explicitly grant write permissions to these accounts on the folder.
 
2.    While uploading the files to a remote server, the default ASPNET user account used by ASP.NET does not have network permissions by default. The solution is to either give the account such permissions or use impersonation to have it run under a different account that has the permissions.
 
3.    By default, you can upload no more than 4096 KB (4 MB) of data. However there is a workaround for this limitation. You can change the maximum file size by changing the maxRequestLength attribute of the httpRuntime element in the web.config file. You can also increase the ‘executionTimeout’. By default it is 110 seconds. I would encourage you to experiment with the other attributes of the httpRuntime element.
<configuration>
      <system.web>
            <httpRuntime
               executionTimeout="200"
               maxRequestLength="8192"
               requestLengthDiskThreshold="256"
               useFullyQualifiedRedirectUrl="false"
               minFreeThreads="8"
               minLocalRequestFreeThreads="4"
               appRequestQueueLimit="5000"
               enableKernelOutputCache="true"
               enableVersionHeader="true"
               requireRootedSaveAsPath="true"
               enable="true"
               shutdownTimeout="90"
               delayNotificationTimeout="5"
               waitChangeNotification="0"
               maxWaitChangeNotification="0"
               enableHeaderChecking="true"
               sendCacheControlHeader="true"
               apartmentThreading="false"/>
      </system.web>
</configuration>
References
There are a number of good resources I referred to, for this article. A few of them are:
http://www.wrox.com/WileyCDA/Section/id-292160.html
http://msdn2.microsoft.com/en-US/library/aa479405.aspx
http://msdn2.microsoft.com/en-us/library/system.web.httpfilecollection.aspx
Conclusion
File uploading in ASP.NET has certainly improved from its earlier versions. However we as developers would like to perform way better than it does today. In this article, I made an attempt to use this control to upload multiple files to the server. I hope this article was useful and I thank you for viewing it.
 If you liked the article,  Subscribe to my RSS Feed.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Jason on Monday, November 5, 2007 1:15 AM
nice code!!! i combined it with a javascript that posts multiple files..so instead of using multiple fileupload controls..i used a single control.. The HttpFileCollection was very helpful...Thanks
Comment posted by chetan thummar on Wednesday, January 2, 2008 1:07 AM
it nice article but if i want to upload multiple file at same time but file control added at run time how many as i want and then upload all posted file at same time.. like attech file in yahoo mail, gmail..   plz help me..
Comment posted by Suprotim Agarwal on Wednesday, January 2, 2008 7:26 AM
Hi chetan, take a look over here http://forums.asp.net/p/1071914/1569254.aspx#1569254
Comment posted by SUNNY on Saturday, March 29, 2008 8:41 AM
path is giving an error in vb.net code its showing path is not declare
Comment posted by Muhammad waqas on Friday, April 11, 2008 2:49 PM
if there should be downloading code of uploaded files
then i think it would be very nice
Comment posted by polesh on Wednesday, April 16, 2008 7:57 AM
Hi nice article.
But instead of placing four fileupload controls at a time. i want to add controls(fileupload) dynamically.
If u Can help me in this .. i'll b very thankful to u
Comment posted by yoonus on Saturday, May 24, 2008 6:17 AM
But instead of placing four fileupload controls at a time. i want to add controls(fileupload) dynamically.
If u Can help me in this .. i'll b very thankful to u
Comment posted by Suprotim Agarwal on Wednesday, May 28, 2008 9:17 AM
You have to use the Page_Init() to create them. What are the issues you face?
Comment posted by Ajay Kelkar on Friday, June 6, 2008 12:32 PM
How can we show progress bar for uploading file
any ideas....
Comment posted by Prem on Tuesday, June 10, 2008 1:24 AM
How to upload a file dynamically in a remote server through Asp.net 2.0.Can anyone help me ? It's Urgent!
Comment posted by Suprotim Agarwal on Tuesday, June 17, 2008 1:12 PM
Ajay: Take a look at this article
http://www.codeproject.com/KB/webforms/File_Upload_Progress_Bar.aspx

Prem: What do you mean by dynamically uploading a file?
Comment posted by Dheeraj Singh on Monday, September 8, 2008 8:02 AM
It is one of the best Article that read for this Particular
Topic.


thanks
Comment posted by Suprotim Agarwal on Monday, September 8, 2008 8:43 AM
Thanks Dheeraj :)
Comment posted by Anand Dave on Monday, October 27, 2008 12:49 PM
i want to add an array of the fileuploadcontrol how can i do it dynamically
Comment posted by Suprotim Agarwal on Wednesday, October 29, 2008 12:32 AM
Anand: Try this post
http://forums.asp.net/t/1156085.aspx
Comment posted by niti on Thursday, November 20, 2008 6:48 AM
i need to upload multiple files without adding multiple fileupload control..

waiting for reply...
plz help
Comment posted by phanideepthi on Saturday, March 21, 2009 5:54 AM
place one fileupload control and one button.when we click button certain no of fileupload controls should be added.can any one help me.
Comment posted by Rob on Saturday, May 9, 2009 7:08 PM
Not a single VB.NET example worked!!!
Comment posted by San on Tuesday, July 7, 2009 3:20 AM
Very nice article, thanx a lot.
Comment posted by echo on Sunday, July 12, 2009 8:15 PM
The name of this article is very misleading. Where does it talk about the “Multiple Files”?
Comment posted by deendayal soni on Tuesday, July 14, 2009 9:16 AM
this is very useful for me.thanking you
Comment posted by Suprotim Agarwal on Friday, July 17, 2009 2:46 AM
echo: Misleading? Are you sure you read the entire article by clicking on the 'Read More' link.

Comment posted by Garima Mishra on Monday, August 10, 2009 6:46 AM
I have a Multiview ,where in to one view i am adding the files and in to another view i am showing the uploaded files . This work i have performed using a session. But as user go back to last view the list of uploaded file get vanish . How can I retrive the list of uploaded Files.Please reply me favourable soon.
Comment posted by Suprotim Agarwal on Tuesday, August 11, 2009 1:12 AM
Garima: That happens since a postback occurs and the values are lost. You can either store the file details using properties or use viewstate or session to retain the values during postback.

Alternatively a non-postback mechanism will do. Check my article here where I have shown how to upload multiple files using jQUery- http://www.dotnetcurry.com/ShowArticle.aspx?ID=317
Comment posted by Johnny on Thursday, September 10, 2009 3:28 AM
Not working when used inside an update panel
Comment posted by Clifford D'Souza on Friday, November 20, 2009 8:13 AM
hey man the article is superb but i have a problem.
i want to configure the way the file list is displayed just as its shown in the link http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Examples
Example 7, 8 , 9 but in asp.net.
i tried a lot of things but without any success.
the code on the above link works fine as html but not if i use the FileUpload control in asp.net.


Help Needed.
Comment posted by Clifford D'Souza on Tuesday, February 9, 2010 2:31 AM
hey man the article is superb but i have a problem.
i want to configure the way the file list is displayed just as its shown in the link http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Examples
Example 7, 8 , 9 but in asp.net.
i tried a lot of things but without any success.
the code on the above link works fine as html but not if i use the FileUpload control in asp.net.
Comment posted by Rukmal on Wednesday, June 2, 2010 10:19 PM
Thank you very much , code helped alot
Comment posted by priya on Tuesday, June 8, 2010 6:37 AM
hey,very good article.......
thanks for such good helpfull article.......
Comment posted by ali on Wednesday, July 28, 2010 10:31 AM
tank you very much becuse  ur cod is very praty.
Comment posted by Wilson Beirigo on Sunday, August 15, 2010 5:44 PM
Hello, thanks for the post. Can you tell me why this code do not work in Visual Studio 2010?
Comment posted by Suprotim on Monday, August 16, 2010 3:19 AM
Wilson: What is the error you get?
Comment posted by Amit Panchal on Tuesday, August 17, 2010 4:00 AM
to upload multiple files using asp.net and c# with jquery visit my blog http://go2amitech.blogspot.com/2010/08/asynchronous-file-upload-in-aspnet.html
Amit Panchal
Comment posted by eric on Saturday, August 28, 2010 3:22 PM
Hello,
You can upload multiple files to multiple file hosting sites (into your account) in EmbedUpload.com .
Just try it.
Comment posted by Waqar Ahmad Bhatti on Thursday, September 16, 2010 2:40 AM
http://waqarahmadbhatti.blogspot.com/2010/09/uploading-file-with-progress-bar-in.html
Comment posted by Mike on Thursday, November 18, 2010 2:43 PM
Nice code - using this code how do you insert filename in database (access db)?

Thanks,

Mike
Comment posted by bhargav on Thursday, December 16, 2010 1:18 AM
is this work in gridview vs2008
Comment posted by Prasad on Tuesday, January 18, 2011 10:10 AM


C# code for many who are looking for multiple upload, it works beautiful

.aspx code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    
    
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<p id="upload-area">
   <input id="File1" type="file" runat="server" size="60" />
</p>

<input id="AddFile" type="button" value="Add file" onclick="addFileUploadBox()" />
<p><asp:Button ID="btnSubmit" runat="server" Text="Upload Now" OnClick="btnSubmit_Click" /></p>
<span id="Span1" runat="server" />

<script type="text/javascript">
    function addFileUploadBox() {
        if (!document.getElementById || !document.createElement)
            return false;

        var uploadArea = document.getElementById("upload-area");

        if (!uploadArea)
            return;

        var newLine = document.createElement("br");
        uploadArea.appendChild(newLine);

        var newUploadBox = document.createElement("input");

        // Set up the new input for file uploads
        newUploadBox.type = "file";
        newUploadBox.size = "60";

        // The new box needs a name and an ID
        if (!addFileUploadBox.lastAssignedId)
            addFileUploadBox.lastAssignedId = 100;

        newUploadBox.setAttribute("id", "dynamic" + addFileUploadBox.lastAssignedId);
        newUploadBox.setAttribute("name", "dynamic:" + addFileUploadBox.lastAssignedId);
        uploadArea.appendChild(newUploadBox);
        addFileUploadBox.lastAssignedId++;
    }
</script>
</form>
</body>
</html>
-------------------------------------------------


.aspx.cs   code


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

public partial class multiplefileupload : System.Web.UI.Page
{
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    hpf.SaveAs(Server.MapPath("Images") + "\\" +
                      Path.GetFileName(hpf.FileName));
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);

        }

    }







}


Comment posted by file upload control in asp.net on Monday, January 31, 2011 5:35 PM
FileUltimate is an ASP.NET file upload control which you can add directly to your existing ASP.NET (.aspx) pages.The control renders a user interface similar to "Windows Explorer" within the page which displays the contents of the target folder and accepts multiple file uploads from users. Actions can be limited by permissions and quota limits on folders. During file uploading, detailed information such as transfer speed and estimated time of completion are displayed along with the progress bar. This ASP.NET upload control supports browser upload,
ajax upload and flash upload modes.
<a href="http://www.gleamtech.com/products/fileultimate/asp-net-file-manager-control" title="file upload control in asp.net">file upload control in asp.net</a>
Comment posted by Sam on Sunday, February 27, 2011 4:49 PM
Hi,

How can i use multiple FileUpload control in one aspx page. Single FileUpload control is working fine.

According to my requirement, I need 2 different FileUpload control to save files at different locations.
I tried using the second FileUpload control, but the problem is how to distinguish which files belong to which FileUpload control.

HttpFileCollection is collecting all the files irrespective of loader.

I mean if Loader 1 is used to upload 2 files
and    if Loader 2 is used to upload 4 files.

HttpFileCollection is collecting all the 6 files. How can i distinguish between these.
Comment posted by Sam on Monday, February 28, 2011 8:42 AM
Hi,

How can i use multiple FileUpload control in one aspx page. Single FileUpload control is working fine.

According to my requirement, I need 2 different FileUpload control to save files at different locations.
I tried using the second FileUpload control, but the problem is how to distinguish which files belong to which FileUpload control.

HttpFileCollection is collecting all the files irrespective of loader.

I mean if Loader 1 is used to upload 2 files
and    if Loader 2 is used to upload 4 files.

HttpFileCollection is collecting all the 6 files. How can i distinguish between these.
Comment posted by bcs on Monday, March 7, 2011 2:33 AM
Hi
   How can you upload a text file (~60mb) to a different server (Oracle) using asp.net? Also how do call an sqlloader through asp.net?
Comment posted by srinivasu dandamudi on Tuesday, March 8, 2011 1:34 AM
it is working fine. but i am unable to upload the files if i use ajax updatepanel,what is the solution.
Comment posted by Shelby Poston on Thursday, April 7, 2011 12:03 PM
I like the code however how would you handle this?
if you want upload files in different directories.

sample code: I have 16 file upload controls for 16 different documents.

System.Web.UI.WebControls.FileUpload inputFile;
                  inputFile = this.FileUpload;
                 if ((!(inputFile.PostedFile == null) && (inputFile.PostedFile.ContentLength > 0)))
                  {
                      // Get the name of the file to be uploaded and
                      // the location where the file needs to be saved.
                      string extension = Path.GetExtension(inputFile.PostedFile.FileName);
                      string saveLocation = (this.Page.Server.MapPath("..\\Data\\" + BUSINESSNAME.Text + "\\"));
                      {
                          try
                          {
                              // Save the file.
                              inputFile.PostedFile.SaveAs(saveLocation + "CSB" + BUSINESSNAME.Text + extension);
                              this.Page.Response.Write("The file has been uploaded.");
                          }
                          catch (Exception ex)
                          {
                              this.Page.Response.Write(("Error: " + ex.Message));
                          }
                          this.Page.Response.Write(" file upload.");
                      }
                  }

so it uploads and changes the file name to CSB + What ever the name of the business name in the text box and with what
ever existing extension.

how would handle something like this.
Comment posted by Shelby Poston on Thursday, April 7, 2011 12:50 PM
I like the code however how would you handle this?
if you want upload files in different directories.

sample code: I have 16 file upload controls for 16 different documents.

System.Web.UI.WebControls.FileUpload inputFile;
                  inputFile = this.FileUpload;
                 if ((!(inputFile.PostedFile == null) && (inputFile.PostedFile.ContentLength > 0)))
                  {
                      // Get the name of the file to be uploaded and
                      // the location where the file needs to be saved.
                      string extension = Path.GetExtension(inputFile.PostedFile.FileName);
                      string saveLocation = (this.Page.Server.MapPath("..\\Data\\" + BUSINESSNAME.Text + "\\"));
                      {
                          try
                          {
                              // Save the file.
                              inputFile.PostedFile.SaveAs(saveLocation + "CSB" + BUSINESSNAME.Text + extension);
                              this.Page.Response.Write("The file has been uploaded.");
                          }
                          catch (Exception ex)
                          {
                              this.Page.Response.Write(("Error: " + ex.Message));
                          }
                          this.Page.Response.Write(" file upload.");
                      }
                  }

so it uploads and changes the file name to CSB + What ever the name of the business name in the text box and with what
ever existing extension.

how would handle something like this.
Comment posted by Nagarjuna on Tuesday, July 5, 2011 9:07 AM
i need to check client side wheather files are added or not before upload button is clicked, how can i do that.
Comment posted by Nagarjuna on Wednesday, July 6, 2011 4:25 AM
How can i check in javascript whether the files are added or not before we click the upload button in sap.net
Comment posted by Nagarjuna on Wednesday, July 6, 2011 5:23 AM
How can i check in javascript whether the files are added or not before we click the upload button in sap.net
Comment posted by Raghu on Saturday, July 16, 2011 2:50 AM
Hi Suprotim,
      Thanks for the article, but I am getting following as soon as I click Upload button :

The connection was reset

      

      
      
      

      
        
        

          

The connection to the server was reset while the page was loading.

        


        
        


    *   The site could be temporarily unavailable or too busy. Try again in a few
          moments.

    *   If you are unable to load any pages, check your computer's network
          connection.

    *   If your computer or network is protected by a firewall or proxy, make sure
          that Firefox is permitted to access the Web.
Comment posted by Vishnu on Tuesday, August 9, 2011 2:56 AM
hi thank you very much its easy to understand...
keep go on like this kind of articles....
Comment posted by busybee1987 on Thursday, October 20, 2011 8:12 AM
You are a genius..No other words to say yaar!!!!
Comment posted by Buvanesh on Saturday, October 29, 2011 9:55 AM
Hi
Multiple upload Files Code I have Deploy in server .Upload time Not get in Upload Full Path ,
the error is Path Access Denied Error.Pls help me
Comment posted by kuloh on Wednesday, November 9, 2011 3:56 PM
thank you very much for the awesome tutorial..it really helped me alot
Comment posted by Safvan on Thursday, July 5, 2012 2:30 AM
with respect to there,
you know how i can fire btnUpload_Click event using ajax..?
i tried lot ways,but its getting zero count in httpfileCollection
i hope your valued help

Thanking you in advance
Thanking you in advance
Comment posted by Darshan on Sunday, October 7, 2012 8:52 AM
How to upload multiple file in asp.net 4.0?
Comment posted by Md Saleh on Friday, February 22, 2013 3:27 AM
here is the easiest way...in the world...after lots of frustration..finally
upload with using any plug-in...

Filename.aspx.cs

protected void btnupload_Click(object sender, EventArgs e)
    {
       string tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
       string savepath = Server.MapPath(tempPath);
        for(int i=0;i<Request.Files.Count;i++)
        {            
            HttpPostedFile hpf = Request.Files[i];
            string filename = hpf.FileName;
            hpf.SaveAs(savepath + @"\" + filename);
        }

    }

Filename.aspx

<div>
        <input type="file" id="FileUpload1" multiple="multiple" runat="server"/>
        <asp:Button runat="server" ID="btnupload" Text="Upload"
            onclick="btnupload_Click"/>&nbsp;<br/>
        <asp:Label runat="server" ID="Label1"></asp:Label>

    </div>

Web.config

<appSettings>
    <add key ="FolderPath" value ="uploads"/>
</appSettings >
Comment posted by Peter on Saturday, February 23, 2013 12:12 AM
Thanks MdSaleh for your code. Hasn't the author also shown something similar? And which plugin are you talking about. The code in this article works just fine~!
Comment posted by Archana on Monday, April 8, 2013 8:48 AM
Want to show preview of image before upload on an image control in asp.net mvc2
Comment posted by marudah on Thursday, April 11, 2013 4:21 PM
A very good article and works great for IE.  I am trying to save the file using a asynchronous callback using ajax.  So btnUpload_Click event code is moved to MultiFileUpload.ashx.  and call the handler on button click event as shown below.  Files.count in ashx is 0.  Can you please give some suggestion how pass this uploaded files to ashx.
$().ready(function () {
        $("#<%=btnUpload.ClientID %>").click(function (e) {
            CalluploaderHandler();
            
        });
    });

    function CalluploaderHandler() {
        $.ajax({
            type: "POST",
          
            url: "../Controls/MultiFileUpload.ashx",
            contentType: "multipart/form-data",
            success: OnComplete,
            error: OnFail
        });
        return false;
    }

    function OnComplete(result) {
        alert('Success');
        return false;
    }

    function OnFail(result) {
        alert('Request failed');
        return false;
    }
Comment posted by marudah on Friday, April 12, 2013 8:23 AM
A very good article and works great for IE.  I am trying to save the file using a asynchronous callback using ajax.  So btnUpload_Click event code is moved to MultiFileUpload.ashx.  and call the handler on button click event as shown below.  Files.count in ashx is 0.  Can you please give some suggestion how pass this uploaded files to ashx.
$().ready(function () {
        $("#<%=btnUpload.ClientID %>").click(function (e) {
            CalluploaderHandler();
            
        });
    });

    function CalluploaderHandler() {
        $.ajax({
            type: "POST",
          
            url: "../Controls/MultiFileUpload.ashx",
            contentType: "multipart/form-data",
            success: OnComplete,
            error: OnFail
        });
        return false;
    }

    function OnComplete(result) {
        alert('Success');
        return false;
    }

    function OnFail(result) {
        alert('Request failed');
        return false;
    }
Comment posted by Meenakshi on Thursday, April 25, 2013 7:25 AM
I am not able to select multiple files at a time.. plz help
Comment posted by Kishore R on Wednesday, July 3, 2013 12:24 AM
Very good article....
Comment posted by ishwar on Thursday, September 26, 2013 7:53 AM
It is working in chrome and Firefox but it is not working in IE

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook