在注册或修改按钮里写:(我这里是2个上传控件分别写方法将其分开)
private void bt_amend_Click(object sender, System.EventArgs e)
{
if(bt_amend.Text=="修改")
{
False();
bt_amend.Text="保存";
bt_clear.Visible=true;
this.Literal1.Text="<script>document.getElementById('File1').style.display=\"block\";</script>";
this.Literal2.Text="<script>document.getElementById('File2').style.display=\"block\";</script>";
}
else
{
try
{
数据库操作(根据数据库中的状态这里为注册)
bt_UP(int.Parse(lab_GoodsID.Text));//调用上传
bt_up2(int.Parse(lab_GoodsID.Text));//调用上传
}
else
{
数据库操作(根据数据库中的状态这里为更新)
bt_UP(int.Parse(lab_GoodsID.Text));//调用上传
bt_up2(int.Parse(lab_GoodsID.Text));//调用上传
}
}
catch
{
Response.Write("<script>alert('操作失败!请重试!');</script>");
}
bt_amend.Text="修改";
tx_Load();
this.Literal1.Text="<script>window.document.getElementById('File1').style.display=\"none\";</script>";
this.Literal2.Text="<script>window.document.getElementById('File2').style.display=\"none\";</script>";
}
}
private void bt_UP(int i)
{
if(!this.Page.IsValid)
{
this.la_UP.Text="您现在不能上传图片!";
return;
}
try
{
HttpPostedFile postFile = FileP1.PostedFile; //读文件
string Path=readFile(postFile,i);//返回的图片名字
if(Path.ToString()!="NO")
{
数据库操作以判断这里是更新库字段
if(dt.Rows.Count>0)
{
File.Delete(@"E:\webdrugstore\GoodsPic\"+DelName.ToString());//取出原由图片名称删除
else
{
数据库操作以判断这里是添加
}
DBServer.ExecuteNonQuery(strSql);
this.la_UP.Text="上传图片成功!";
}
else
{
this.la_UP.Text="上传图片失败!请重试!";
}
}
catch (Exception ex)
{
this.la_UP.Text="上传图片失败!请重试!"+ex.Message;
}
}
private void bt_up2(int i)
{
if(!this.Page.IsValid)
{
this.la_UP2.Text="您现在不能上传图片!";
return;
}
try
{
HttpPostedFile postFile = FileP1.PostedFile; //读文件
string Path=readFile(postFile,i);//返回的图片名字
if(Path.ToString()!="NO")
{
数据库操作以判断这里是更新库字段
if(dt.Rows.Count>0)
{
File.Delete(@"E:\webdrugstore\GoodsPic\"+DelName.ToString());//取出原由图片名称删除
else
{
数据库操作以判断这里是添加
}
DBServer.ExecuteNonQuery(strSql);
this.la_UP.Text="上传图片成功!";
}
else
{
this.la_UP.Text="上传图片失败!请重试!";
}
}
catch (Exception ex)
{
this.la_UP.Text="上传图片失败!请重试!"+ex.Message;
}
}
private string MakeFielPath(HttpPostedFile hpf,int i)//查找文件存放目录并且生成唯一文件名
{
string filePath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath) + "\\" + "\\goodsPic";
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
string Name=hpf.FileName;
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss")+DateTime.Now.Millisecond.ToString()+"_"+i.ToString()+Name.Substring(Name.LastIndexOf("."));//获取唯一文件名
hpf.SaveAs(filePath + "\\" + fileName);
return fileName;
}
private string readFile(HttpPostedFile postFile,int i)//验证文件格式
{
if( Path.GetExtension(postFile.FileName).ToLower() ==".jpg" || Path.GetExtension(postFile.FileName).ToLower() ==".jpeg"
|| Path.GetExtension(postFile.FileName).ToLower() ==".gif" || Path.GetExtension(postFile.FileName).ToLower() ==".bmp")
{
return MakeFielPath(postFile,i);
}
else
{
return "NO";
}
}