将图像文件上载到MDF数据库

时间:2014-09-23 15:06:55

标签: c# asp.net file-upload

我正在尝试将图像文件上传到MDF数据库:“ImageMDFdb”。

我在表格中指定了一个列:“ImageTable”,其中包含Image的属性。

            string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
            string ext = System.IO.Path.GetExtension(FileUpload1.FileName);
            byte[] Image = null;
            if (ext == "jpg" | ext == "gif" | ext == "bmp")
            {
                Image = new byte[FileUpload1.PostedFile.ContentLength];
                HttpPostedFile UploadedImage = FileUpload1.PostedFile;
                UploadedImage.InputStream.Read(Image, 0, (int)FileUpload1.PostedFile.ContentLength);
                try
                {
                    string connStr = ConfigurationManager.ConnectionStrings["ImageMDFdb"].ConnectionString;
                    string cmdStr = "INSERT INTO [ImageTable] VALUES (@filename,@ext,@image);";
                    using (SqlConnection conn = new SqlConnection(connStr))
                    {
                        using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
                        {
                            conn.Open();
                            cmd.Parameters.AddWithValue("@filename", filename);
                            cmd.Parameters.AddWithValue("@ext", ext);
                            cmd.Parameters.AddWithValue("@image", Image);
                            cmd.ExecuteNonQuery();
                            conn.Close();
                            cmd.Dispose();
                            conn.Dispose();
                        }

                    }


                }
                catch (Exception ex)
                {
                    Label2.Text = "INSERT INTO: " + ex.ToString();
                }
            }

0 个答案:

没有答案