图片存入数据库

protected System.Web.UI.HtmlControls.HtmlInputFile ImageToUpload;

   string ContentType = ImageToUpload.PostedFile.ContentType;
   string str = ImageToUpload.PostedFile.FileName;
   /// <summary>
   /// Length holds the size of the file that was added to the ImageToUpload control </summary>
   int Length = System.Convert.ToInt32(ImageToUpload.PostedFile.InputStream.Length);

   if (Length == 0)
   {
    Response.Write("<script language=javascript>alert('图片太小了')></script>");
    return;
   }

   /// <summary>
   /// Content will hold the image. It is a byte array of size Length </summary>
   byte[] Content = new byte[Length];

   /// <summary>
   /// The Read method is used to read the file from the ImageToUpload control </summary>
   ImageToUpload.PostedFile.InputStream.Read(Content,0,Length);

   /// <summary>
   /// Open a connection to the SQL Server </summary>
   SqlConnection Connection = new SqlConnection("server=localhost;uid=sa;pwd=;database=ImageUpload");
   /// <summary>
   /// The SqlCommand will be used to insert the image into the Images table </summary>
   SqlCommand Command = new SqlCommand("INSERT Into Images(Description, ImageFile, ImageSize, ImageType) Values(@Description, @ImageFile, @ImageSize, @ImageType)", Connection);

   /// <summary>
   /// The Description parameter is used to add the image file description to the database
   SqlParameter imageDescriptionParameter = new SqlParameter("@Description", SqlDbType.NVarChar);
   imageDescriptionParameter.Value = imageDescription.Text;
   Command.Parameters.Add(imageDescriptionParameter);

   /// <summary>
   /// The ImageFile parameter is used to add the image file to the database
   SqlParameter imageFileParameter = new SqlParameter("@ImageFile", SqlDbType.Image);
   imageFileParameter.Value = Content;
   Command.Parameters.Add(imageFileParameter);

   /// <summary>
   /// The ImageSize parameter is used to add the image file size to the database
   SqlParameter imageSizeParameter = new SqlParameter("@ImageSize", SqlDbType.Int);
   imageSizeParameter.Value = Length;
   Command.Parameters.Add(imageSizeParameter);

   /// <summary>
   /// The ImageType parameter is used to add the image file type to the database
   SqlParameter imageTypeParameter = new SqlParameter("@ImageType", SqlDbType.NVarChar);
   imageTypeParameter.Value = ContentType;
   Command.Parameters.Add(imageTypeParameter);

   /// <summary>
   /// Open the connection in order to retrieve the record </summary>
   Connection.Open();
   /// <summary>
   /// The SQL statement is executed. ExecuteNonQuery is used since no records
   /// will be returned. </summary>
   Command.ExecuteNonQuery();
   /// <summary>
   /// The connection is closed </summary>
   Connection.Close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值