Uploading Multiple Files Using ASP.NET 2.0 Client Callbacks
By AzamSharp
Views: 2526

Introduction:

 

Uploading files is a common behavior of any web application. In this article I will explain how to upload multiple files using ASP.NET Client Callbacks.

 

Creating the User Interface:

 

I am going to create a Gmail like interface for attaching files. If you are not familiar with that approach then I suggest that you create a Gmail account and check it out yourself. For those lazy people who don’t want to create an account here is the small description of the procedure.

 

The page consists of a single HREF link which allows creating input FILE elements to attach multiple files. All the steps are performed by using JavaScript. Let’s dive into the code and see what is going on.

 

Here is the HREF link I was talking about:

 

<a href="#" onclick="attachFile()">Attach a file</a> 

 

The attachFile function creates the INPUT FILE element and appends to the existing DIV element.

 

function attachFile()

{

    var fu = document.createElement("INPUT"); 

    fu.type = "file";

   

   

    var br = document.createElement("<BR>");

     

    document.getElementById("fileDivBox").appendChild(fu);

    document.getElementById("fileDivBox").appendChild(br);

}

 

The document.createElement(“INPUT”) creates the TextBox by default so, we need to explicitly specify [object].type = “file” to make it a FILE element. The fileDivBox is a simply DIV element placed inside the ordered list element as shown below:

 

<ol>

       <li style="list-style:none">

       <div id="fileDivBox" />

       </li>    

    </ol>

 

Uploading the File:

 

The actual file upload is performed by the uploadFile function which is called when the “Upload” file button is clicked.

 

<input type="button" value="Upload" onclick="uploadFile()" />

 

var selectedFiles = '';

 

 

function ReceiveServerData(response)

{

   alert(response); 

}

 

function uploadFile()

{

    var fileList = document.getElementById("fileDivBox").getElementsByTagName("INPUT");

   

    for(i=0; i<fileList.length;i++)

    {

        selectedFiles +=  fileList[i].value + "|";

    }

   

    CallServer(selectedFiles,'');  

}

 

 

The selectedfiles is a global JavaScript variable which is used to collect all the selected files separated by the “|” sign. Once, all the files are collected they are sent to the server using client callbacks.

 

The Server Side Code:

 

The server side code starts with implementing the ICallbackEventHandler. I am not going to explain how to register callbacks as I have done so in almost all of my client callback articles. Instead I will jump to the GetCallbackResult method where I used the “|” separated list and upload the files one by one.

 

  public void RaiseCallbackEvent(string eventArgument)

        {

            string[] files = (eventArgument.TrimEnd('|')).Split('|');

 

            WebClient client = new WebClient();

 

            foreach (string file in files)

            {

                    client.UploadFile("http://localhost:1566/FileServer.aspx", "POST", file);

            }  

        }

 

The WebClient class in ASP.NETprovides necessary methods to upload the file. The WebClient’s UploadFile method is used to upload a file to a URI from where it can be uploaded to the server. In this example the files are uploaded to the FileServer.aspx page and from there they are sent to the server’s folder.

 

Let’s check out the code on FileServer page which is used to upload the files to the server’s folder.

 

  protected void Page_Load(object sender, EventArgs e)

        {

            // server folder

            string path = @"C:\UploadedFiles\";

            string[] keys = Request.Files.AllKeys;

 

            foreach(String key in keys)

            {

                HttpPostedFile file = Request.Files[key];

                file.SaveAs(path + file.FileName);

            }

          

        }

 

Not complicated at all right!

 

Simply, iterate through the Request.Files.AllKeys collection and get all the keys. Finally, iterate though the keys and get the file and then upload the file to the server.

 

Conclusion:

 

Uploading files can be a tedious task in web applications. In this article I discussed how to upload multiple files using ASP.NET 2.0 Client Callbacks. If you are uploading large files then I recommend uploading them in bits and pieces instead of uploading the whole file at one go.

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Nice But Missing
Name: Faheem Ahmad
Date: 11/19/2007 12:00:23 AM
Comment:
This is a nice tutorial but it does not give the facility to download sample code.
Subject: RE: Nice but missing!
Name: AzamSharp
Date: 11/19/2007 7:18:22 AM
Comment:
Hi Faheem Ahmad, I do appreciate your concern. Please try to make the most of it by using the code samples provide above.
Subject: Problem with FileServer.aspx Page
Name: Imran Ahmad Mughal
Date: 11/25/2007 12:00:20 AM
Comment:
I really impressed from your articals. Dear I impleted uploading multiple file uploading with client calback but i found a problem when giving a path in client.upload(). Please tell me the where I place FileServer.aspx page so that i don't get an error. Thanks
Subject: RE: Problem with FileServer.aspx page
Name: AzamSharp
Date: 11/27/2007 12:31:33 PM
Comment:
Hi Imran, You can place the FileServer.aspx page in your root folder of you application.
Subject: Worked in IE but not in FireFox
Name: Imran Ahmad Mughal
Date: 12/3/2007 11:35:28 PM
Comment:
I hope that you will be fine and working hard in your professinal field. I have a question which when we click on attachFile button in IE, it works find append the file upload control and break line in div, but when i try to run it in firefox, the problem is that when i click on attachFile button no file upload and break line appended in the div. Can you tell me the reason why this is not working in FireFox.
Subject: RE: Worked in IE but not in FireFox
Name: AzamSharp
Date: 12/5/2007 1:43:52 PM
Comment:
Hi Imran,

Thanks for letting me know about this problem. I will fix this issue and post the solution as soon as I can.

Thanks!
Subject: Scorecard
Name: Vishwanathan
Date: 2/8/2008 5:57:07 AM
Comment:
I need to create a scorecard in asp.net how to do it?
Subject: webclient can't find the file
Name: ekoprasetio
Date: 4/21/2008 12:54:34 AM
Comment:
hi azamsharp, this is nice but i encounter some problem. I deploy this code on my pc, and from other pc, it will try to upload some files. but the problem is, on this part of the code:
foreach (string file in files)

{

client.UploadFile("http://localhost:1566/FileServer.aspx", "POST", file);

}
the file is actually the path from other pc (client) and the server read it as its own path. this will not work of course because the path is not in the server. so how am i going to use this upload file?
Subject: RE: Webclient can't find the file
Name: AzamSharp
Date: 4/22/2008 9:55:40 AM
Comment:
Hi Ekoprasetio, I have not tried this scenario. It might be that the WebClient only uploads the file that is residing on the local machine OR there might be a security problem associated with your scenario.
Subject: CallServer(selectedFiles,'');
Name: HA
Date: 4/23/2008 2:06:59 AM
Comment:
CallServer(selectedFiles,'');
What is the functionality of this call. I am unable to get the call on server. Please help me our
Subject: CallServer
Name: Harry
Date: 4/23/2008 2:30:31 AM
Comment:
(selectedFiles,'');
I am unable to get this. Could u pls tell me how to call the server event.



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008