ASP.NET save files from dynamically added FileUpload controls
I'm building an ASP.NET UserControl where users of the website can upload several pictures at once. I'm doing it the old fashioned way by letting the user enter the amount of FileUpload controls wanted and then add them dynamically from C# to a asp:Panel control.
While this works, the values/files from the FileUpload isn't stored for when the user clicks the "Save" button. How exactly do I开发者_运维技巧 go about this problem?
My code for specifying the amount of FileUpload controls wanted:
protected void btnSubmitImageAmount_Click(object sender, EventArgs e)
{
int amountOfControls = Convert.ToInt32(txtImageAmount.Text);
for (int i = 0; i < amountOfControls; i++)
{
FileUpload fUl = new FileUpload();
Label lblLineBreak = new Label();
lblLineBreak.Text = "<br />";
fUl.ID = i.ToString();
fUl.Visible = true;
pnlUploadControls.Controls.Add(fUl);
pnlUploadControls.Controls.Add(lblLineBreak);
}
}
Code for the Save button:
protected void btnCreateStory_Click(object sender, EventArgs e)
{
List<Media> images = new List<Media>();
foreach (Control ctrl in pnlUploadControls.Controls)
{
if (ctrl is FileUpload)
{
FileUpload fUl = (FileUpload)ctrl;
Media media = UmbracoSave(fUl, storydDoc.Id);
if (media != null)
{
images.Add(media);
}
}
}
}
Anyone got any hints of how to solve this problem? :)
Thanks in advance!
You need to re-create the dynamic controls on every postback, or they will no longer exist.
I suggest reading this article and learning more about the page life cycle.
When using dynamic FileUpload remember to manually set Page.Form.Enctype = "multipart/form-data"; It is encoding type that allows files to be sent through a POST - for more information see What does enctype='multipart/form-data' mean?
精彩评论