打印本文 打印本文 关闭窗口 关闭窗口
将图片插入数据库并使用asp.net读取出来的正确方法
作者:武汉SEO闵涛  文章来源:敏韬网  点击数4151  更新时间:2009/4/23 10:45:58  文章录入:mintao  责任编辑:mintao
292, 273);

           this.Controls.Add(this.insertButton);

           this.Controls.Add(this.browseButton);

           this.Controls.Add(this.filePath);

           this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;

           this.MaximizeBox = false;

           this.Name = "MainForm";

           this.Text = "Insert Image to Database";

           this.ResumeLayout(false);

 

       }

       #endregion

 

       /// <summary>

       /// The main entry point for the application.

       /// </summary>

       [STAThread]

       static void Main()

       {

           Application.Run(new MainForm());

       }

 

       private void browseButton_Click(object sender, System.EventArgs e)

       {

           if(openFileDlg.ShowDialog()==DialogResult.OK)

           {

              filePath.Text=openFileDlg.FileName;

              insertButton.Enabled=true;

           }

       }

 

       private void insertButton_Click(object sender, System.EventArgs e)

       {

           FileStream fs=File.OpenRead(filePath.Text);

           byte[] content=new byte[fs.Length];

           fs.Read(content, 0,content.Length);

           fs.Close();

 

           SqlConnection conn=new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DatabaseImage;Data Source=(local)");

           conn.Open();

 

           SqlCommand comm=conn.CreateCommand();

           comm.CommandText="insert into Images(Image, contentType) values(@image, @contentType)";

           comm.CommandType=CommandType.Text;

 

           SqlParameter param=comm.Parameters.Add("@image", SqlDbType.Image);

           param.Value=content;

           comm.Parameters.Add("@contentType", SqlDbType.NVarChar).Value=

              GetContentType(new FileInfo(filePath.Text).Extension.Remove(0,1));

 

           if(comm.ExecuteNonQuery()==1)

           {

              MessageBox.Show("Successfully insert image into database!");

           }

           else

           {

              MessageBox.Show("Failed to insert image into database");

           }

 

           conn.Close();

       }

 

       private string GetContentType(string extension)

       {

上一页  [1] [2] [3] [4] [5] [6]  下一页

打印本文 打印本文 关闭窗口 关闭窗口