內容面板收納
分享: facebook PLURK twitter
把FileUpload的檔案(圖檔)上傳至MS Sql中,然後從資料庫讀出後,利用ashx的泛型處理轉成二進位位元組,呈現在GridView中。
建置:
Create Table UploadImg(
id int identity(1,1),
images image null
)
上傳:
//上傳圖片
//定義位元組
byte[] imagebyte = new byte[this.FileUpload1.PostedFile.ContentLength];
//把fileupload載入位元組
imagebyte = FileUpload1.FileBytes;
cmd.Parameters.Add("@images", SqlDbType.Image).Value = imagebyte;
try
{
cn.Open();
cmd.ExecuteNonQuery().ToString();
}
catch (Exception Err)
{
}
finally
{
cn.Close();
}
File.ashx:負責把資料庫的圖檔轉成二進位
public void ProcessRequest (HttpContext context) {
int id = int.Parse(context.Request.QueryString["id"]);
using (SqlConnection conn = new SqlConnection(連線字串))
{
string sql = "select images from [upload] where id=@id";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
context.Response.ContentType = "image/jpg";
context.Response.BinaryWrite((byte[])dr["Images"]);
}
dr.Close();
}
}
GridView的設定:只要指定圖片的來源路徑就ok了。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" >
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:ImageField DataImageUrlField="id" DataImageUrlFormatString="file.ashx?id={0}"
HeaderText="Images">
</asp:ImageField>
</Columns>
</asp:GridView>