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();
}
}
}
沒有留言:
張貼留言