測試文字功能,小工具,標題

記錄很重要,不然會浪費很多時間在找以前的記憶

一個人的氣度,決定他未來的高度。

2016年5月27日 星期五

ASP.NET 存 取 二進位圖檔

ASP.NET 存 取 二進位圖檔

讀取要先建立一個ToImage.ashx

===============ToImage.ashx======================================

 public void ProcessRequest(HttpContext context)
        {
        // //   context.Response.ContentType = "text/plain";
        // //   context.Response.Write("Hello World");
            try
            {
                using (SqlConnection cn = new SqlConnection())
                {
                    SqlCommand cmd = new SqlCommand();

                    cn.ConnectionString = ConfigurationManager.ConnectionStrings["lswConnectionString"].ConnectionString;

                    cn.Open();

                    cmd.Connection = cn;

                    cmd.CommandText = "SELECT question_pic FROM question_m WHERE question_old = @question_old";

                    cmd.Parameters.Add("@question_old", SqlDbType.NVarChar).Value = context.Request.QueryString["question_old"];
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        context.Response.ContentType = "image/jpeg";
                        context.Response.BinaryWrite((byte[])dr["question_pic"]);
                    }
                    cn.Close();
                }
            }
            catch (Exception ex)
            {

            }
 }


========================= html=======================

 <asp:ImageField
                    HeaderText="圖示" ReadOnly="True"
                    SortExpression="question_old" DataImageUrlField="question_old"
                    DataImageUrlFormatString="~/ToImage.ashx?question_old={0}">
                </asp:ImageField>

===============存到 DB==============================

        private void question_add()
        {
            string queryString = @"INSERT INTO question_m (question_pic) VALUES (@question_pic)";

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                try
                {
                    using (SqlCommand cmd = new SqlCommand(queryString, conn))
                    {
                       //上傳圖檔
                        cmd.Parameters.AddWithValue("@question_pic", FileUpload1.FileBytes);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                    }
                }
                catch (Exception err)
                {
                    lbl_err.Text = err.Message;
                }
                finally
                {
                    conn.Close();
                }
            }         
        }

沒有留言:

張貼留言