先在Page_Load方法添加点击事件
protected void Page_Load(object sender, EventArgs e)
{
btnUploadFile2.ServerClick += new EventHandler(btnUploadFile2_ServerClick);
}
再在方法实现事件中增加常用的一些写法
void btnUploadFile2_ServerClick(object sender, EventArgs e)
{
try
{
if (TxtMedCode2.Text.Length == 0)
{
Page.RegisterStartupScript("msg", "<script>alert('请先填写药品编码再进行图片添加!')</script>");
return;
}
//1.上传文件
bool fileOK = false;
string path = Server.MapPath("~/upload/");
if (this.FileUpload2.HasFile)
{
string fileException = System.IO.Path.GetExtension(FileUpload2.FileName).ToLower();
string[] allowedException = { ".jpg", ".gif", ".bmp", ".ico", ".png" };
for (int i = 0; i < allowedException.Length; i++)
{
if (fileException == allowedException[i])
fileOK = true;
}
}
if (fileOK)
{
try
{
DateTime dt1 = DateTime.Now;
//保存原始图片至upload路径
string strFileName = this.TxtMedCode2.Text.ToString() + dt1.ToString("yyyyMMddHHmmss");
this.FileUpload2.SaveAs(path + strFileName + "_Init" + ".jpg");
//获取图片的原始路径,并生成image格式标准图
System.Drawing.Image img_Big = this.PhotoSizeChange(path + strFileName + "_Init" + ".jpg", 300, 165);
//保存标准图片至upload路径
img_Big.Save(path + strFileName + "_Commendation" + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
//将即将保存的标准图片路径赋值给图片地址记录签
LblImgUrl2.Text = "upload/" + strFileName + "_Commendation" + ".jpg";
//
if (Mn_PostId(TxtMedCode2.Text) == "0")
{
//LblDeatil1.Text = "查无此药品,请添加此药品后再进行设置!";
}
else
{
LblPostUrl2.Text = Mn_PostId(TxtMedCode2.Text);
}
//Img1.ImageUrl = LblImgUrl1.Text.ToString();
//关闭标准图对象
img_Big.Dispose();
//this.LblDeatil1.Text = "文件上传成功!";
}
catch (Exception ex)
{
Response.Redirect("~/Error.aspx?error=" + ex.Message.Replace("<br>", "").Replace("\n", ""));
Page.RegisterStartupScript("msg", "<script>alert('上传文件失败,请重试!')</script>");
}
}
else
{
Page.RegisterStartupScript("msg", "<script>alert('请上传文件!')</script>");
}
}
catch (Exception e2)
{
Response.Redirect("~/Error.aspx?error=" + e2.Message.Replace("<br>", "").Replace("\n", ""));
}
}
改变图像长和宽的方法如下
private System.Drawing.Image PhotoSizeChange(string strPhoto, int iWidth, int iHeight)
{
//*****strPhoto是原来的图片文件所在的物理路径******//
//处理图片功能
System.Drawing.Image image = new Bitmap(strPhoto);//得到原图
//创建指定大小的图
System.Drawing.Image newImage = image.GetThumbnailImage(iWidth, iHeight, null, new IntPtr());
Graphics g = Graphics.FromImage(newImage);
//将原图画到指定的图上
g.DrawImage(newImage, iHeight, iHeight, newImage.Width, newImage.Height);
g.Dispose();
return newImage;
}