Store image in database and retrieve it

后端 未结 4 1494
深忆病人
深忆病人 2021-01-28 07:36

My code for inserting image in database is as follows:

MemoryStream ms =new MemoryStream();
byte[] PhotoByte=null;
PhotoByte=ms.ToArray();
pictureBox1.Image.Save         


        
4条回答
  •  遥遥无期
    2021-01-28 08:18

    It is possible of course to store your images in db. However it is not recommended. It is better to store them in a file system.

    Your code is a bit messy. The following is a better example.

    MemoryStream ms =new MemoryStream(); 
    byte[] PhotoByte=null; 
    pictureBox1.Image.Save(ms, ImageFormat.Jpeg); 
    PhotoByte =ms.ToArray(); 
    // I'm not sure whether you are able to create an sql by simply concating the string
    Str = "insert into Experimmm Values('@PhotoBytes','@MyTextValue')"; 
    // You have to parametrize your query
    cmd.Parameters.AddWithValue("PhotoBytes", PhotoByte);
    // This also helps you to avoid syntactical corruption in case of ' and sql injection
    cmd.Parameters.AddWithValue("MyTextValue", textBox1.Text );
    Conn.Open(); 
    cmd.Connection = Conn; 
    cmd.CommandText = Str; 
    cmd.ExecuteNonQuery(); 
    Conn.Close(); 
    

    When you retrieve you could use a binary writer in some handler

    namespace TestNS
    {
       public class MyHttpHandler : IHttpHandler
       {
          // Override the ProcessRequest method.
          public void ProcessRequest(HttpContext context)
          {
             // Your preparations, i.e. querystring or something
             var conn = new SqlConnection("Your connectionstring");
             var command = new SqlCommand("Your sql for retrieval of the bytes", conn);
             conn.Open();
             var data = (Byte[])command.ExecuteScalar();
             conn.Close();
             context.Response.BinaryWrite(data);      }
    
          public Boolean IsReusable
          {
             get { return false; }
          }
       }
    }
    

提交回复
热议问题