How to handle multiple file upload dynamically


Introduction

Recently I worked on a site in which we were required to upload multiple files.

That was really nice and I decided to put the code here.

1) How to add  file upload control dynamically. 

Here is the code,

if (Session["i"] == null)
{
    Session["i"] = i;
}
else
{
    i = Convert.ToInt32(Session["i"].ToString());
    i++;
    Session["i"] = i;
}
i = Convert.ToInt32(Session["i"].ToString());
string str = Server.MapPath("upload");
FileUpload fop = new FileUpload();
fop.ID = "FileUpload" + i.ToString();
FileUpload123.Controls.Add(fop);
Session["fop" + i.ToString()] = fop;

In the above code I am adding file upload control dynamically to my div with id FileUpload123 by following code

FileUpload fop = new FileUpload();
fop.ID = "FileUpload" + i.ToString();
FileUpload123.Controls.Add(fop);

Here ID is used to give id in sequence; it is of type int32 declared at top.

And also I am adding that in my session because whenever post back occurs this control will be removed so at next step I am taking it from my session variable.

2) How to make all controls not removable after postback.

Here is the code,

protected void Page_Init(object sender, EventArgs e)
{
    if ( Session["i"] == null )
    {
        Session["i"] = i;
    }
    else
    {
        i = Convert.ToInt32(Session["i"].ToString());
        for (int j = 0; j < i + 1; j++)
        {
            FileUpload fop = (FileUpload)Session["fop" + j.ToString()];
            fop.Style.Add("margin-bottom", "10px");
            FileUpload123.Controls.Add(fop);
            //  FileUpload123.Controls.Add("<br/>");
        }
    }
}

Again taking all the controls from session and put them in the page.

And now finally,

3) How to upload the files from dynamically added controls

Here is the code,

i = Convert.ToInt32(Session["i"].ToString());
string str = Server.MapPath("upload");
for (int j = 0; j < i + 1; j++)
{
    FileUpload fp = (FileUpload)FileUpload123.FindControl("FileUpload" + j.ToString());
    if (fp.HasFile)
    {
        fp.SaveAs(str + "\\" + fp.FileName);
    }
}

As all the fileupload controls are added dynamically we don't know how many there are so with the above code I have uploaded my files.

Note: I am storing all the controls in the session for the particular this case if we just increase one variable by one and place the controls dynamically with that variable then that's really good but as per my requirement we have not just do this with fileupload control but also with textbox and also we have to remember the value of that textbox so I have choosen this way. And I have not done this with fileupload control I have done this with usercontrol.

Any way thanks for reading...


Similar Articles