圖片檔案從資料庫讀取並直接輸出至 HTTP 回應流,避免暫存檔。
private void ImgDataRead() {
int imgId = Convert.ToInt32(Request.QueryString["id"]);
using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"])) {
string sql = "SELECT * FROM ImageStore WHERE ID = @ImageID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("@ImageID", SqlDbType.Int).Value = imgId;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
Response.ContentType = (string)dr["ImageContentType"];
Response.OutputStream.Write((byte[])dr["ImageData"], 0, Convert.ToInt32(dr["ImageSize"]));
Response.BufferOutput = true;
con.Close();
}
}
註解區展示替代寫法:讀入 MemoryStream 再建立 Bitmap 指派給 PictureBox。