protected void BtnSubmit_Click(object sender, EventArgs e) { { try { MyConn = DB.CreateDB();
string title =FunStr(this.TxtTitle.Text);//转换 string content =FunStr(this.TxtContent.Text); string ptype = Request.QueryString["action"].ToString(); string FileName = myFile.Value; HttpPostedFile UpFile = myFile.PostedFile; //获取对由客户端指定的上传文件的访问 FileLength = UpFile.ContentLength;//获取上传文件的字节大小 if (FileLength == 0) { MyConn.Open(); OleDbCommand cmd1 = new OleDbCommand("insert into product(pro_name,title,content) values('" + ptype + "','" + title + "','" + content + "')",MyConn); cmd1.ExecuteNonQuery(); Response.Write("<script>alert('数据添加成功');window.location.href='Admin_Add.aspx?action=" + ptype + "'</script>"); MyConn.Close(); } else { string exName = FileName.Substring(FileName.LastIndexOf(".") + 1).ToUpper();//截取图片的后缀名,改名 if (exName == "JPG" || exName == "BMP" || exName == "GIF")//判断图片的类型 { if (FileLength > 1024000)//判断图片是否大于200k(根据自己的需要判断大小) { Response.Write("<script>alert('对不起,图片大小不能大于1M');window.location.href='Admin_Add.aspx?action=" + ptype + "'</script>"); return; } else { string ImageName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + "." + exName;//图片名称设置为保存的时间 Byte[] FileByte = new Byte[FileLength]; //图象文件储存到数组 Stream ObjectStream = UpFile.InputStream;//建立数据流对像,获取一个 Stream 对象,该对象指向一个上载文件,以准备读取该文件的内容。
ObjectStream.Read(FileByte, 0, FileLength); //读取图象文件数据 string StrSql = "Insert Into product(pro_name,img,title,content) Values('" + ptype + "',@ImageName,'" + title + "','" + content + "')"; OleDbCommand Cmd = new OleDbCommand(StrSql, MyConn); //Cmd.Parameters.Add("@Image",OleDbType.Binary, FileLength).Value = FileByte; Cmd.Parameters.Add("@ImageName", OleDbType.VarChar, 100).Value = ImageName; MyConn.Open(); this.myFile.PostedFile.SaveAs(Server.MapPath("/upload") + "\\" + ImageName); Cmd.ExecuteNonQuery(); MyConn.Close(); Response.Write("<script>alert('数据添加成功');window.location.href='Admin_Add.aspx?action="+ptype+"'</script>"); } } else { Response.Write("<script>alert('对不起,请选择正确的的图片!');window.location.href='Admin_Add.aspx?action=" + ptype + "'</script>"); return; } }
} catch (Exception ex) { Response.Write("<script>alert('" + ex.Message + "')</script>"); } }
}
|