WebForm中动态批量文件上传

在WebForm中动态添加FileUpload控件和实现批量文件上传。

Web.config配置:

<appSettings>
<add key="FileUpLoadPath" value="~/Content/Upload/"/>
<add key="FileTypeLimit" value=".jpg,.gif"/>
<add key="FileSizeLimit" value="1024000"/>
</appSettings>

前台代码:

<table class="gbtext" id="tb_UploadedFiles" style="BORDER-COLLAPSE: collapse" borderColor="#93bee2"
cellSpacing
="0" cellPadding="0" width="100%" align="center" border="1" runat="server">
<tr>
<td style="WIDTH: 94px"><font face="宋体">上传数量:</font></td>
<td>
<asp:DropDownList ID="ddl_USL" runat="server" AutoPostBack="True"
onselectedindexchanged
="ddl_USL_SelectIndex">
<asp:ListItem Value="0" Text="请选择"></asp:ListItem>
<asp:ListItem Value="1" Text="1个"></asp:ListItem>
<asp:ListItem Value="2" Text="2个"></asp:ListItem>
<asp:ListItem Value="3" Text="3个"></asp:ListItem>
<asp:ListItem Value="4" Text="4个"></asp:ListItem>
<asp:ListItem Value="5" Text="5个"></asp:ListItem>
<asp:ListItem Value="6" Text="6个"></asp:ListItem>
<asp:ListItem Value="7" Text="7个"></asp:ListItem>
<asp:ListItem Value="8" Text="8个"></asp:ListItem>
<asp:ListItem Value="9" Text="9个"></asp:ListItem>
<asp:ListItem Value="10" Text="10个"></asp:ListItem>
</asp:DropDownList>
</td>

</tr>
<tr>
<td style="WIDTH: 94px"><font face="宋体"></font></td>
<td>
<asp:Panel ID="pl_UF" runat="server">

</asp:Panel>
</td>
</tr>
<tr>
<td style="WIDTH: 94px"><font face="宋体"></font></td>
<td><font face="宋体">
<input type="submit" value="上传" class="ButtonCss" />
</font></td>
</tr>
</table>

后台代码:

protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (Request.Files.AllKeys.Any())
{
var apath
= ConfigurationManager.AppSettings["FileUpLoadPath"];
var fileSize
= Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]);
string path=Server.MapPath(apath);
try
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
foreach (string f in Request.Files.AllKeys)
{
if (Request.Files[f].ContentLength == 0) continue;
if (Request.Files[f].ContentLength > fileSize) continue;//图片大于配置文件大小不上传

string filename = Path.GetFileName(Request.Files[f].FileName);
Request.Files[f].SaveAs(Path.Combine(path, filename));
pl_UF.Controls.Add(
new Label { Text = filename + "上传成功!" });
pl_UF.Controls.Add(
new Literal { Text = "<br />" });
}
}
catch (Exception ex)
{
Response.Redirect(
"~/Error?error=" + ex.Message);
}
}
}
}

protected void ddl_USL_SelectIndex(object sender, EventArgs e)
{
int sl = Convert.ToInt32(ddl_USL.Items[ddl_USL.SelectedIndex].Value);
if (sl != 0)
{
for (int x = 0; x < sl; x++)
{
pl_UF.Controls.Add(
new FileUpload { ID = "FU"+x.ToString() });
pl_UF.Controls.Add(
new Literal { Text = "<br />" });
}
}
}

实现效果:

 

 

 

posted on 2011-04-06 16:15  Ω元素  阅读(690)  评论(2编辑  收藏  举报

导航