This example presents options to add
FileUpload control at runtime; a user can create as many
FileUploads as required at runtime and can enter values in them.
It also presents a feature to access the values stored in these runtime
Generating controls at run time can sometimes be unavoidable, but unfortunately it is something .NET guys talk less about.
Once I got an assignment to add any number of images for an entity, this required displaying
FileUpload controls at runtime.
Being a beginner at that time, I was quite overwhelmed by enormous articles present on this topic, I wished I could find something simple.
I found a solution of my problem with a hit and trial method. I would like to share this small, simple but useful webpage that demonstrates the Generating and Accessing FileUploads at runtime. I created it when I just started learning .NET. It is not quite perfect, but presents the bare minimum functionality.
I hope it could be helpful to someone.
Using the Code
First, let’s look at the aspx page:
Adding Attachment(s)<br />
<input type="button" onclick="addAttach()" value="More Attachments"
id="btnAddNewUpload" style="width: 140px" />
<asp:FileUpload ID="fuFirst" runat="server" /><br />
<asp:Button ID="btnSaveFiles" runat="server" OnClick="Button1_Click"
Text="OK" Width="60px" />
<asp:Button ID="brnCancel" runat="server" Text="Cancel" Width="70px" />
Div divAttachments will serve as a container for our runtime
Adding new FileUpload
btnAddNewUpload will trigger the creation of new
addAttach on click event.
addAttach is very simple; it will add a new file control to our
var str ="<input type='file' name='File' /><br>"
insertAdjacentHTML inserts a new element at the specified position. It takes the position of new element in the parent element as first parameter, and the new element to be added as second parameter.
Accessing Values of these Runtime FileUploads
btnSaveFiles will try to access the values of all the
FileUploads created at runtime. Let’s look at the event.
First, we need to find out the collection of all the posted files present in current request. We can do this as:
HttpFileCollection hfcFiles = Request.Files;
Then we can iterate through this collection and save the files one by one.
for (int i = 0; i < hfcFiles.Count; i++)
HttpPostedFile file = hfcFiles[i];
string strExtension = Path.GetExtension(file.FileName);
file.SaveAs(Server.MapPath("file" + i + strExtension));
It should be known that we can find extension of any file name using
Path.GetExtension method. We need to extract the extension to compare against acceptable file extensions and create a specific file name.
I am saving the file as it is, you can add your code to check any specific extension or file existence, etc.
- 14th April, 2010: Initial post