HttpFileCollection files = Request.Files;
for (int i = 0; i < files.Count;i++ )
{
HttpPostedFile file = files[i] as HttpPostedFile;
string path = Server.MapPath("/UpLoadImg/"); // 上传路径
// 得到上传的文件名
string fileName = Path.GetFileName(file.FileName);
if (string.IsNullOrEmpty(fileName))
{
this.areaErrorMsg.Text = "提示:请选择文件!";
return;
}
// 限制上传文件的大小 4M
if (file.ContentLength > 1024 * 4)
{
this.areaErrorMsg.Text = "提示:上传的文件超过允许的上限!";
return;
}
// 得到上传文件的类型
string fileType = Path.GetExtension(fileName);
string typeExtension = ".jpg.gif";
// 限制上传文件的类型
if (typeExtension.IndexOf(fileType) != -1)
{
// 创建文件夹
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// 如果文件已经存在,则改变文件名
if (File.Exists(path + fileName))
{
// 重命名文件 精确到毫秒
fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + fileName;
}
if (fileName.Length > 50)
{
fileName = fileName.Substring(0, 50);
}
// 保存
file.SaveAs(path + fileName);
}
else
{
this.areaErrorMsg.Text = "提示:上传的文件不是允许的类型!";
}
}