C#笔记之文件上传
//上传照片
protected void btnUpLoadImage_Click(object sender, EventArgs e)
{
//判断是否有文件
if (!this.fulStuImage.HasFile) return;
//判断文件大小
double fileLength = this.fulStuImage.FileContent.Length / (1024.0 * 1024.0);
if (fileLength>1.0)
{
this.ltaMsg.Text = "<script> alert('上传的图片不得超过1MB') </script>";
return;
}
//获取文件后缀名,是否符合格式,前后台双层验证
string fileName = this.fulStuImage.FileName;
fileName = fileName.Substring(fileName.LastIndexOf(".")).ToLower();
if (fileName!=".jpg")
{
this.ltaMsg.Text = "<script> alert('上传图片仅支持.jpg格式!') </script>";
return;
}
//修改文件名为指定格式
fileName = ViewState["Id"].ToString() + ".jpg";
try
{
string filePath = Server.MapPath("~/Images/Student");
this.fulStuImage.SaveAs(filePath + "/" + fileName);
//上传成功跳转到添加页面
this.ltaMsg.Text = "<script> alert('图片上传成功!');location='AddStudent.aspx' </script>";
}
catch (Exception ex)
{
this.ltaMsg.Text = "<script> alert('图片上传失败!"+ex.Message+"') </script>";
}
}