Insert Image to a database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mathewgk80
    New Member
    • Sep 2007
    • 103

    Insert Image to a database

    Hi all,

    I would like to know how to insert an image to a database table using asp.net,c#.net and sql server.

    Please help me.

    regards,

    Mathew
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    I typed your exact title into google:

    Comment

    • hbxtlhx
      New Member
      • Sep 2007
      • 10

      #3
      example:

      public static void AddEmployee(
      string lastName,
      string firstName,
      string title,
      DateTime hireDate,
      int reportsTo,
      string photoFilePath,
      string connectionStrin g)
      {
      byte[] photo = GetPhoto(photoF ilePath);

      using (SqlConnection connection = new SqlConnection(
      connectionStrin g))

      SqlCommand command = new SqlCommand(
      "INSERT INTO Employees (LastName, FirstName, " +
      "Title, HireDate, ReportsTo, Photo) " +
      "Values(@LastNa me, @FirstName, @Title, " +
      "@HireDate, @ReportsTo, @Photo)", connection);

      command.Paramet ers.Add("@LastN ame",
      SqlDbType.NVarC har, 20).Value = lastName;
      command.Paramet ers.Add("@First Name",
      SqlDbType.NVarC har, 10).Value = firstName;
      command.Paramet ers.Add("@Title ",
      SqlDbType.NVarC har, 30).Value = title;
      command.Paramet ers.Add("@HireD ate",
      SqlDbType.DateT ime).Value = hireDate;
      command.Paramet ers.Add("@Repor tsTo",
      SqlDbType.Int). Value = reportsTo;

      command.Paramet ers.Add("@Photo ",
      SqlDbType.Image , photo.Length).V alue = photo;

      connection.Open ();
      command.Execute NonQuery();
      }
      }

      public static byte[] GetPhoto(string filePath)
      {
      FileStream stream = new FileStream(
      filePath, FileMode.Open, FileAccess.Read );
      BinaryReader reader = new BinaryReader(st ream);

      byte[] photo = reader.ReadByte s((int)stream.L ength);

      reader.Close();
      stream.Close();

      return photo;
      }

      Comment

      Working...