【ASP.NET】 GridView 数据库图片 续
Since the images are stored in a database (BLOB),
we need to retrieve the image as a byte array and do a binary write for the images to display in the webpage.
HTTPHandler
Synchronous HttpHandler
Asynchronos HttpHandler
Synchronous HttpHandler should implement System.Web.IHttpHandler
Asynchronous HttpHandler should implement System.Web.IHttpAsyncHandler
同步的, IHttpHandler成员有两个
ProcessRequest()
This method is the core of HttpHandler as it does all the processing of an HttpHandler.
IsReusable
This property specifies whether the HttpHandler can be reused for similar request.
具体步骤:
a. 添加一个Image Control,设置ImageUrl属性
imImage.ImageUrl = '<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>'
b. 对于GridView来说,添加一列ImageField, 设置属性
<asp:ImageField DataImageUrlField="ImageID"
DataImageUrlFormatString="ImageHandler.ashx?ImID={0}" HeaderText="Image">
</asp:ImageField>
构建一个页面ImageHandler.aspx负责fetches the image from database and do a BinaryWrite .i.e. the final code will be like,
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("select Image from ImageTable where ImageID="+imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
ProcessRequest方法是如何get the access of Response object? 看ProcessRequest方法签名
public void ProcessRequest (HttpContext context) {}
The context object will give access to necessary object about the request.
通过它我们可以do a BinaryWrite using Response object.
context.Response.BinaryWrite((Byte[])dr[0]);
Thumbnail
通过这种方法的缺陷是:it will stretch the gridview column based on the dimensions of the images stored
因此用Thumbnail的形式,加上click放大的功能,就更好了。
popup in window
1. Crete a Thumbnail.ashx
<ItemTemplate>
<a href="javascript:void(window.open('<%# "FullImageHandler.ashx?ImID="+ Eval("ImageID")%>','_blank','toolbar=no,menubar=no'))" >
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ThumbnailHandler.ashx?ImID="+ Eval("ImageID") %>'/>
</a>
</ItemTemplate>
</asp:TemplateField>
图片是经过ThumbnailHandler.ashx处理了,点击图片,调用JavaScript window.open
Popup in same page
有些浏览器可能关闭了popup window,因此更好的方式是将FullImage放在同一个页面的<Div>里,设置display:none
点击thumbnail image, we can enable the DIV tag through a javascript function and pass the ImID of the image to call the FullImage.ashx HttpHandler for displaying the full image in the <img> tag.
执行结果
代码下载: Source Code (实现了上传的功能)
另:
建立局域网的web 服务,publish你的website后,要设置IIS的站点属性 Web site Identification的IP Address为本机的IP地址,不能是“未分配”
还有要修改你的APP_DATA文件夹写的属性,默认是只读的,不能写入数据库。
参考:
HttpHandler in ASP.Net: PART 1
HttpHandler in ASP.Net: PART 2
GridView with Thumbnail Images – Part 1 in codedigest
ThumbNail Image Creation By Rick
出处:http://www.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。