protected void Button3_Click(object sender, EventArgs e)
{
//定义变量,判断是否有图片上传
bool fileIsValid = false;
//如果有图片上传,判断其格式
if (this.FileUpload1.HasFile)
{
int len = this.FileUpload1.PostedFile.ContentLength;
if (len / 1024 > 60)
{
this.Label1.Text = "图片太大了";
return;
}
else
{
string type = this.FileUpload1.PostedFile.ContentType;
if (type == "image/pjpeg")
{
fileIsValid = true;
}
else
{
this.Label1.Text = "图片格式不支持";
return;
}
}
if (fileIsValid == true)
{
try
{
//产生随机数用于设置图片名称
Random r = new Random();
//获取当前时间+随机数
string time = DateTime.Now.ToString("yyyyMMdd")+ r.Next().ToString();
//获取图片路径
string filePath = this.FileUpload1.FileName;
//获得图片后缀名
string strName = Path.GetExtension(filePath).ToLower();
string fileName = "~/images/" + time + strName;
// ClientScript.RegisterStartupScript(this.GetType(), "", "alert('" +strName+","+ filePath+","+fileName + "')", true);
//定义图片路径用于显示图片
this.Image1.ImageUrl = fileName;
//保存图片
this.FileUpload1.SaveAs(Server.MapPath(fileName));
this.Label1.Text += "<br>";
this.Label1.Text = "图片上传成功!";
this.Label1.Text += "<li>"+"原文件路径:"+this.FileUpload1.PostedFile.FileName;
this.Label1.Text += "<br>";
this.Label1.Text += "<li>" + "图片大小:" + this.FileUpload1.PostedFile.ContentLength+"字节";
this.Label1.Text += "<br>";
this.Label1.Text += "<li>" + "图片类型:" + this.FileUpload1.PostedFile.ContentType;
}
catch
{
this.Label1.Text = "图片上传失败!";
}
finally
{
}
}
else
{
this.Label1.Text = "图片上传失败!";
}
}
}