我在ASPX
页面添加了一些动态控件。我需要动态添加它们,因为控件的数量取决于数据库记录。
我正在使用UpdatePanel
并动态添加控件:
void AddFileUploadFields()
{
for (int i = 0; i < Helper.uploadFieldsCount; i++)
{
FileUpload fileUpload = new FileUpload();
string controlId = DateTime.Now.Ticks.ToString();
Thread.Sleep(10); // for non-equal ID for each control
fileUpload.ID = controlId;
uploadFormsId.Add(controlId);
UpdatePanel1.ContentTemplateContainer.Controls.Add(fileUpload);
PlaceHolder1.Controls.Add(fileUpload);
}
}
然后从按钮,在asp-tag <asp:Button ... />
中静态定义我正在尝试处理我要上传的文件信息:
void buttonUpload_Click(object sender, EventArgs e)
{
var iEnum = uploadFormsId.GetEnumerator();
List<UploadFormDetails> uploadsInfo = new List<UploadFormDetails>();
List<string> generatedFileNames = new List<string>();
bool wereErrors = false;
while (iEnum.MoveNext())
{
FileUpload uploadForm = (FileUpload)FindControl(iEnum.Current.ToString());
uploadsInfo.Add(new UploadFormDetails(uploadForm.ID, uploadForm.HasFile, uploadForm.FileName));
}
...
}
主要问题确实发生在这里:
FileUpload uploadForm = (FileUpload)FindControl(iEnum.Current.ToString());
当我获得这样的控制权时,它的所有选项(例如.HasFile
或.FileName
)都无法查看。它看起来像一个没有保存选项的新控件。当然,我正在为测试选择一些文件,请不要认为我是在尝试从空表格上传。
我该怎么办呢?我无法上传任何文件...
答案 0 :(得分:0)
我找到了一个解决方案,但我得到的结果是以其他方式设计的,它不使用ASP.NET的Server controls
,我处理了普通的HTML
元素。
在ASPX页面中,我定义了:
<%
for (int i = 0; i < Helper.uploadFieldsCount; i++)
{
Response.Write("<input type='file' id='uploadField" + i.ToString() + "' name='uploadField" + i.ToString() + "' class='file_1' /><br />");
}
%>
runat
在页面的主要形式中定义,开头:
<body>
<form enctype="multipart/form-data" id="form1" runat="server">
...
在CodeBehind
我正在使用基于GUID
的随机生成的名称上传新文件:
void buttonUpload_Click(object sender, EventArgs e)
{
List<string> generatedFileNames = new List<string>();
bool wereErrors = false;
for (int i = 0; i < Helper.uploadFieldsCount; i++)
{
HttpPostedFile filePosted = Request.Files["uploadField" + i.ToString()];
if (filePosted != null && filePosted.ContentLength > 0)
{
string fileNameApplication = System.IO.Path.GetFileName(filePosted.FileName);
string fileExtensionApplication = System.IO.Path.GetExtension(fileNameApplication);
string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
string filePath = System.IO.Path.Combine(Server.MapPath("uploads"), newFile);
if (fileNameApplication != String.Empty)
{
generatedFileNames.Add(newFile);
filePosted.SaveAs(filePath);
}
}
...