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.

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 the id FileUpload123 by following the 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 the top.

Also, I am adding that in my session because whenever postback occurs this control will be removed so at the next step I am taking it from my session variable.

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 take all the controls from the session and put them on the page.

And now finally

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 file upload 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 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 done this with file upload control but also with a textbox and also we have to remember the value of that textbox so I have chosen this way. And I have not done this with file upload control I have done this with user control.

Anyway, thanks for reading.


Similar Articles