Wednesday, October 15, 2008

Uploading Multiple Files in ASP.NET

In this post I have given code for uploading multiple files using client callback.
Here I will not explain client callback as I have published a dedicated post on it.

Now, this multiple files upload functionality has 4 parts:

1. Selecting multiple files functionality and Upload button functionality that will request the client callback in FileUpload.aspx page .

2. Implementing ICallbackHandler interface by defining GetCallbackResult and RaiseCallbackEvent methods in the FileUpload.aspx.cs file. RaiseCallbackEvent methods will call UploadFile method of WebClient class, which posts the file to the given url(in our case it is fileserver.aspx).

3. Saving functionality for uploaded file on the server in Fileserver.aspx file.

Here is the sample code.

I have not explained it in details as it is self explainatory yet I have commented code as and when required.

----------------------------------------------------------------------
File - FileUpload.aspx

< script language="javascript" type="text/javascript">
var selectedFiles = '';

function CallbackResultHandler(result, context) //this function will receive the callback result
{
alert(result);
}
// below function will receive callback resulted appended with error msg when server throws an error
function CallbackErrorHandler(result, context)
{
alert("Error: " + result);
}
function uploadFile() // this function will trigger the callback
{
var fileList = document.getElementById("divUploadFile").getElementsByTagName("INPUT");
for(i=0; i < fileList.length;i++)
{
selectedFiles += fileList[i].value + "|";
}
< %=_callbackRef % > // here callback method - WebForm_doCallback will be rendered.
}

function attachFile()
{
var varTag1 = document.createElement("INPUT");
varTag1.type = "file";
var varTag2 = document.createElement("< BR >");
document.getElementById("divUploadFile").appendChild(varTag1);
document.getElementById("divUploadFile").appendChild(varTag2);
}

< /script >

< html xmlns="http://www.w3.org/1999/xhtml">
< head runat="server">
< title >File Upload Page< /title >
< /head >
< body >
< form id="form1" runat="server" >
< div >
< table >
< tr >
< td colspan="2">
< ol >
< li style="list-style: none">
< div id="divUploadFile" / >
< /li >
< /ol >
< /td >
< /tr >
< tr >
< td >
< a href="#" onclick="attachFile()">Attach a file< /a >
< /td >
< td >
< input type="button" value="Upload" onclick="uploadFile()" / >
< /td >
< /tr >
< /table >
< /div >
< /form >
< /body >
< /html >

------------------------------------------------------------------
File - FileUpload.aspx.cs

public partial class FileUpload : System.Web.UI.Page, ICallbackEventHandler
{
string _result = string.Empty;
protected string _callbackRef = string.Empty;

protected void Page_Load(object sender, EventArgs e)
{
//following code returns the javascript call to WebForm_doCallback function
_callbackRef = ClientScript.GetCallbackEventReference(this, "selectedFiles", "CallbackResultHandler","null", "CallbackErrorHandler", true);
}

#region ICallbackEventHandler Members

public string GetCallbackResult() //returnd the callback result
{
return _result;
}

public void RaiseCallbackEvent(string eventArgument) // invokes callback event
{
string[] Files = (eventArgument.TrimEnd('|')).Split('|');
System.Net.WebClient Client = new System.Net.WebClient();
try
{
string Url = "http://localhost:" + Request.Url.Port.ToString() +
"/FileUploadWebsite/FileServer.aspx";
foreach (string file in Files)
{
Client.UploadFile(Url, "POST", file);
}
_result = "All files are uploaded successfully.";
}
catch (System.Net.WebException ex)
{
_result = "One or more file(s) could not be uploaded.";
throw ex;
}
}

#endregion
}

-------------------------------------------------------------
File - Fileserver.aspx

< script runat="server" >
void Page_Load(object sender, EventArgs e)
{
string Uploadpath = @"C:\TestWeb\UploadedFiles\"; // ASPNET account should have read/write permission on the folder

string[] Keys = Request.Files.AllKeys;
foreach (String key in Keys)
{
HttpPostedFile File = Request.Files[key];
File.SaveAs(Uploadpath + File.FileName);
}
}
< /script >

< html xmlns="http://www.w3.org/1999/xhtml" >
< head runat="server" >
< title >File Server Page< /title >
< /head >
< body >
< form id="form1" runat="server">
< div >

< /div >
< /form >
< /body >
< /html >

2 comments:

Ajeet said...

i used what u write there,but is is not working in case of masterpage concept.
can u please tell me how i will use it.

Anonymous said...

How do we get this to work now that most browsers are not returning full path for the value attribute of file control?