Ajax 加載數據庫中的圖片
1,ashx頁面
<%@ WebHandler Language="C#" Class="GetImage" %> using System; using System.Web; using System.Data; using System.IO; public class GetImage : IHttpHandler { public void ProcessRequest(HttpContext context) { SQLHelper sqlH = new SQLHelper(); string strID = context.Request["ID"]; byte[] MyData = new byte[0]; string str = " select [ImageData] from [Leave] where [ID]='" + strID + "' "; DataTable dt = sqlH.ExecuteQuery(str, CommandType.Text); if (dt.Rows.Count > 0) { MyData = (byte[])dt.Rows[0][0]; int ArraySize = MyData.GetUpperBound(0); context.Response.OutputStream.Write(MyData, 0, ArraySize); } } public bool IsReusable { get { return false; } } }
2,aspx頁面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>无标题页</title> <script type="text/javascript"> function LoadImage(ElementID, id) { //ElementID <img>的ID var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //WebClient if (!xmlhttp) { alert("創建xmlhttp對象異常"); return false; } var url = "GetImage.ashx?ID=" + id + "&ts" + new Date(); xmlhttp.open("POST", "GetImage.ashx?ID=" + id + "&ts" + new Date(), false); xmlhttp.onreadystatechange = function event() { if (xmlhttp.readystate == 4) { if (xmlhttp.status == 200) { document.getElementById(ElementID).src = url; } else { alert("Ajax返回Error"); } } } xmlhttp.send(); } </script> </head> <body> <form id="form1" runat="server"> <div> <img id="Image" alt="" src="" /> <input id="Text1" type="text" /> <input id="Button1" type="button" value="button" onclick="LoadImage('Image', '004')" /> </div> </form> </body> </html>