Saturday, May 19, 2007

Uploading Multiple Files

Sometime in your web application, especially the ones which is working with files, you may need to upload more than one file in a web page. While you don't know how many files you have to upload it seems to be a good way to create a control which can upload one or more dynamically.

The first thing that I 'm going to do is to place a FileUpload control in my control and a button for upload and a link for a new file upload control. Like this:

<div>FileName: <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:LinkButton ID="lnkAddMore" Text="Add More..." runat="server"OnClick="lnkAddMore_Click"></asp:LinkButton> <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /><br /> <div runat="server" id="divFileUpload"> </div></div>

notice that, inside the last div I put another div which is a server html control.

Then in the link button event handler I wrote some codes like this:


protected void lnkAddMore_Click(object sender, EventArgs e)
{
FileUpload fileUpload = new FileUpload();
Literal lt = new Literal();
lt.Text = "<br/>";

divFileUpload.Controls.Add(fileUpload);
divFileUpload.Controls.Add(lt);

AddedControls.Add(fileUpload);
AddedControls.Add(lt);
}

I put the "AddedControls" property on the control which is List to keep all the added controls in the Session. The point is that we have to keep them to add in each and every post back.


protected List AddedControls
{
get
{
if (Session["AddedControls"] == null)
Session["AddedControls"] = new List();
return (List)Session["AddedControls"];
}
set
{
Session["AddedControls"] = value;
}
}

So, for adding this controls every time I create the event handler for "PreInit" event:


protected void Page_PreInit(object sender, EventArgs e)
{
foreach (Control ctrl in AddedControls)
{
divFileUpload.Controls.Add(ctrl);

}
}

In the last part, I 'm saving all the uploaded files using "Request.Files" property in Upload button event handler:


protected void btnUpload_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile file = (HttpPostedFile)Request.Files[i];
if (file.ContentLength > 0)
{
try
{
file.SaveAs(Request.PhysicalApplicationPath + "\\UploadedFiles\\" + file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1));
}
catch (Exception ex)
{
Response.Write("" + ex.Message + "");
continue;
}
}
}
}

in HttpPostedFile class there is a SaveAs method which I 'm using to save my files to the server. The method need a physical path so I provide it by Request.PhysicalApplicationPath.

You can download the sample code here:
http://www.tabatabaei.info/dynamicfileupload.zip

3 comments:

Anonymous said...

not working
enumerator error

DHARAV said...

it's not working dude..

JammerX19 said...

My file upload objects go blank after clicking the "add more" link. Your source code link is busted so I can't see how you got around this. Thoughts?