图片上传原理个人见解

时间:2021-10-27 05:02:25

最近客户提到一个图片上传下载的问题:发现自己对这里的原理也是似懂非懂。

结合下面代码说下自己的见解:

首先选择图片

当选中OK 后

读取图片的名称,设置读取的方式等

然后利用byte[] 类型获取图片的内容读取到文件流中。

最后更新数据库。

 

 openImageFile.Filter = "JPEG文件|*.jpg";
            openImageFile.Title = "选择图片文件";
            try
            {
                if (openImageFile.ShowDialog() == DialogResult.OK)
                {
                    FileStream fs = File.Open(openImageFile.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);

 

                        byte[] data = new byte[fs.Length];
                        fs.Read(data, 0, data.Length);
                        if (partNoClass.Part_Picture.Rows.Count == 0)
                        {
                            DataRow dr_Picture = partNoClass.Part_Picture.NewRow();

                            dr_Picture[PartNoClass.F_PICTURE_SEQ] = 1;

                            partNoClass.Part_Picture.Rows.Add(dr_Picture);
                        }
                        partNoClass.Part_Picture.Rows[0][PartNoClass.F_PART_PICTURE] = data;

                        fs.Close();
                        fs.Dispose();
                    
                }
            }
            catch (Exception ex)
            {
                UpdateProcessStatus(ProcessStatus.Failed, ex.Message);
                MserpClientException.RegistError(ex);
            }

 

 

对于如何读取图片自己没有研究

特此附上网上查找的一段代码可以备用

private void button2_Click(object sender, System.EventArgs e)
 {
  //打开数据库连接
  if( conn.State == ConnectionState.Open)
   conn.Close();
  ConnectionString ="Integrated Security=SSPI;" + "Initial Catalog=mydb;" +"Data Source=localhost;";
  conn.ConnectionString = ConnectionString;

  // 创建数据适配器
  string sql="SELECT * FROM ImageStore" ;
  SqlCommand command = new SqlCommand(sql, conn);
 
  try
  {conn.Open();}
  catch(Exception newerr)
  {
   MessageBox.Show(" 不能打开数据联接!") ;
  }
  finally
  {}

  SqlDataReader dr = command.ExecuteReader();
  if(dr.Read())
  {
   FileInfo fi = new FileInfo("temp");
   FileStream myStream=fi.Open(FileMode.Create);
   byte[] mydata=((byte[])dr["imgdata"]);
   //label2.Text="您现在看到的是:"+ dr["imgtitle"].ToString();
   foreach(byte a in mydata)
   {
    myStream.WriteByte(a);
   }
  myStream.Close();
  Image myImage=Image.FromFile("temp") ;
  pic1.Image=myImage; ----pic1 为 PictureBox控件的id
  pic1.Refresh();
  dr.Close ();

 }
 else
 {
  MessageBox.Show("没有成功读入数据!") ;
 
 }

 conn.Close();

}

}