- private void btnUpload_Click(object sender, System.EventArgs e)
- {
- //得到用户要上传的文件名
- string strFilePathName = loFile.PostedFile.FileName;
- string strFileName = Path.GetFileName(strFilePathName);
- int FileLength = loFile.PostedFile.ContentLength;
- if(FileLength<=0)
- return;
- try
- {//上传文件
- Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
- Stream StreamObject = loFile.PostedFile.InputStream; //建立数据流对像
- //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
- StreamObject.Read(FileByteArray,0,FileLength);
- //建立SQL Server链接
- string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
- SqlConnection Con = new SqlConnection(strCon);
- String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
- SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
- CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
- CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = loFile.PostedFile.ContentType; //记录文件类型
- //把其它单表数据记录上传
- CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = tbDescription.Text;
- //记录文件长度,读取时使用
- CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = FileLength;
- Con.Open();
- CmdObj.ExecuteNonQuery();
- Con.Close();
- //跳转页面
- Response.Redirect("ShowAll.aspx");
- }
- catch
- {
- }
- }
- //2.DataGrid控件绑定数据
- //程序代码
- private void Page_Load(object sender, System.EventArgs e)
- {
- string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
- SqlConnection con = new SqlConnection(strCon);
- SqlDataAdapter da = new SqlDataAdapter("Select * from ImageStore",con);
- DataSet ds = new DataSet();
- da.Fill(ds,"image");
- dgShow.DataSource = ds.Tables["image"].DefaultView;
- dgShow.DataBind();
- }
- //3.显示数据库图片数据
- 程序代码
- private void Page_Load(object sender, System.EventArgs e)
- {
- int ImgID = Convert.ToInt32(Request.QueryString["ID"]); //ID为图片ID
- //建立数据库链接
- string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
- SqlConnection Con = new SqlConnection(strCon);
- String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
- SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
- CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID;
- Con.Open();
- SqlDataReader SqlReader = CmdObj.ExecuteReader();
- SqlReader.Read();
- Response.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型
- //输出图象文件二进制数制
- Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);
- Response.End();
- //也可以保存为图像
- // FileStream fs = new FileStream(@"C:/aa.BMP", FileMode.OpenOrCreate, FileAccess.Write);
- // fs.Write((byte[])SqlReader["ImageData"], 0,(int)SqlReader["ImageSize"]);
- // fs.Close();
- Con.Close();
- }
向sql数据库中存取照片
最新推荐文章于 2020-11-05 15:40:57 发布