private bool fileUpLoad()
{
if (txtFup.HasFile)
{
string fileContentType = txtFup.PostedFile.ContentType;//获取客户端上传文件的类型
if (fileContentType == "image/gif" || fileContentType == "image/pjpeg")//文件类型如果为gif或者jpg的话,条件为true
{
string name = txtFup.PostedFile.FileName;//获取客户端文件名
FileInfo file = new FileInfo(name);//对name进行包装,创建file对象
string fileUpName = System.DateTime.Now.ToString("yyyyMMdd") + file.Name;
filename = fileUpName;
string serverPath = Server.MapPath("upload/images/" + fileUpName);//获取服务器路径
string creatServerPath = "upload/images";//创建服务器路径
if (!File.Exists(serverPath))//判断是否存在文件
{
try
{
if (txtFup.PostedFile.ContentLength > 1024000)//判断上传文件大小
{
this.RegisterClientScriptBlock("", "<script language='javascript'>alert('上传文件不能大于1024K'):history.go(-1);</script>");
return false;
}
if (Directory.Exists(Server.MapPath(creatServerPath )) == false)//判断是否存在服务器文件路径
{
Directory.CreateDirectory(Server.MapPath(creatServerPath));
}
txtFup.SaveAs(serverPath);//使用saveas方法保存文件
return true;
}
catch (Exception ex)
{
this.Page.RegisterClientScriptBlock("", "<script language='javascript'>alert('上传图片失败!失败原因:" + ex.Message + "')</script>");
return false;
}
}
else
{
this.Page.RegisterClientScriptBlock("", "<script language='javascript'>alert('相片也存在,请重新上传!')</script>");
return false;
}
}
else
{
this.Page.RegisterClientScriptBlock("", "<script language='javascript'>alert('图片类型不符!')</script>");
return false;
}
}
return false;
}
来源:https://www.cnblogs.com/xiaochen88/archive/2012/12/26/2833730.html