private string SavePhoto(bool isEdit,string oldimgpath)
{
string filePath="";
string allowedExt = "|.jpg|.gif|.jpeg|.png|.bmp|";
int maxFileSize = 409600;//400KB
HttpPostedFile postedFile = System.Web.HttpContext.Current.Request.Files["Img"];
string fileExt = Path.GetExtension(postedFile.FileName).ToLower();
//检测文件类型是否合法
if(!isEdit)
{
if(allowedExt.IndexOf("|" + fileExt + "|")==-1)
{
Response.Write("<script language='JavaScript' type='text/JavaScript'>alert('文件类型不合法,只能上传jpg gif类型文件!');</script>/n");
Response.End();
}
if(postedFile.ContentLength==0)
{
Response.Write("<script language='JavaScript' type='text/JavaScript'>alert('请选择您要上传的文件!');</script>/n");
Response.End();
}
if(postedFile.ContentLength>maxFileSize)
{
Response.Write("<script language='JavaScript' type='text/JavaScript'>alert('上传文件大小超出限制,最大只能上传 400KB 的文件!');</script>/n");
Response.End();
}
Random ro=new Random(System.Guid.NewGuid().GetHashCode());
string tempPath = @"Upload/" + System.DateTime.Now.ToString("yyyy") + @"/" + System.DateTime.Now.ToString("MMdd") + @"/";
filePath = tempPath + DateTime.Now.ToString("yyyyMMddHHmmss") + ro.Next(10000) + fileExt;
Functions.CreateFilePath(ConfigurationSettings.AppSettings["PersonalPath"] + tempPath);
postedFile.SaveAs(ConfigurationSettings.AppSettings["PersonalPath"] + filePath);
}
else
{
if(postedFile.ContentLength !=0)
{
if(allowedExt.IndexOf("|" + fileExt + "|")==-1)
{
Response.Write("<script language='JavaScript' type='text/JavaScript'>alert('文件类型不合法,只能上传jpg gif类型文件!');</script>/n");
Response.End();
}
if(postedFile.ContentLength>maxFileSize)
{
Response.Write("<script language='JavaScript' type='text/JavaScript'>alert('上传文件大小超出限制,最大只能上传 400KB 的文件!');</script>/n");
Response.End();
}
//删除原有图片
if( oldimgpath!=null && oldimgpath !=string.Empty)
{
string pImgPath = ConfigurationSettings.AppSettings["PersonalPath"] + oldimgpath;
if(System.IO.File.Exists(pImgPath))
System.IO.File.Delete(pImgPath);
}
Random ro=new Random(System.Guid.NewGuid().GetHashCode());
string tempPath = @"Upload/" + System.DateTime.Now.ToString("yyyy") + @"/" + System.DateTime.Now.ToString("MMdd") + @"/";
filePath = tempPath + DateTime.Now.ToString("yyyyMMddHHmmss") + ro.Next(10000) + fileExt;
Functions.CreateFilePath(ConfigurationSettings.AppSettings["PersonalPath"] + tempPath);
postedFile.SaveAs(ConfigurationSettings.AppSettings["PersonalPath"] + filePath);
}
else
{
filePath = oldimgpath;
}
}
return filePath;
}