aspx控件:FileUpload
<asp:FileUpload ID="FileUpload1" runat="server" />
如果要一次上传多个文件 控件属性设置:AllowMultiple="True"
代码:
如果.NET Framework为4.5及以上的 可以使用“GetMultiple”方法
HttpFileCollection hc = HttpContext.Current.Request.Files;
var files = hc.GetMultiple("FileUpload1");
foreach (HttpPostedFile item in files)
{
}
如果是4.5以下的
HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
if (hfc.Count > 0)
{
if (hfc[0].ContentLength < 1000000)
{
string ImgExtend = getExtend(hfc[0].FileName);
if (ImgExtend == ".bmp" || ImgExtend == ".jpg" || ImgExtend == ".gif" || ImgExtend == ".png")
{
string path = "UpFiles\\WebPageImage\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + FromUserName;
if (Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("/") + path) == false)
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("/") + path);
}
content = DateTime.Now.ToString("yyyyMMddHHmmssfff") + (new Random()).Next().ToString().Substring(0, 4) + getExtend(hfc[0].FileName);
savepath = System.Web.HttpContext.Current.Server.MapPath("/") + path + "\\" + content;
file = "\\" + path + "\\" + content;
Session["ImgPath"] = file;
hfc[0].SaveAs(savepath);
str = "上传成功";
}
else if (ImgExtend == "")
{ }
else
{
str = "上传的图片格式只能是jpg、png!";
}
}
else
{ str = "上传的图片大小为1M以下!"; }
}