显示VARBINARY作为一个可下载的链接 [英] Display varbinary as a downloadable link
问题描述
相当简单的问题,我都存储在我的数据库为varbinary图像和想提供一个链接到这些图像,而不是在网站上显示它们。当用户点击链接时,他/她应该能够下载图像。
Fairly straightforward question, I have images stored in my database as varbinary and would like to provide a link to these images rather than displaying them on the website. When a user clicks the link he/she should be able to download the image.
推荐答案
这是图像供应响应请求。
An image is served in response to a request.
<img src="?" /> <!-- what goes here? -->
您需要创建一个 HTTP处理程序来接收这些图片的请求。
You need to create an HTTP handler to receive requests for these images.
一个处理程序是指可以响应您的请求特定的URL提供一个可执行文件;在这种情况下,由服务的图像的二进制数据。一个ASPX页面是一个有效的处理程序,虽然有更高效的处理器类型的图像。
A handler is an executable available at a specific URL which can respond to your request; in this case, by serving the binary data of an image. An ASPX page is a valid handler, though there are more efficient handler types for images.
<img src="MyHandler.aspx?imageId=123" />
的处理程序应该做的几件事情:
The handler should do a few things:
- 确认该ID是否有效,以及调用方具有权限(如果需要)
- 从数据库中检索图片
- 设置合适的响应头
- 使用
Response.BinaryWrite()
来的比纳尔数据发送到客户端。
- validate that the ID is valid and that the caller has permissions (if needed)
- retrieve the image from the database
- set appropriate response headers
- use
Response.BinaryWrite()
to send the binar data to the client.
请注意,如果你正在使用ASP.Net MVC,您可以使用控制器的处理器。
Note that if you are using ASP.Net MVC, you can use a controller as your handler.
另一种方法是立足64 EN code中的字节,并直接在图像标签嵌入他们。
An alternative method is to base 64 encode the bytes and embed them directly in the image tag.
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
这是小的图像或一个有用的技术,当多个请求的费用是非常高的。
This is a useful technique for small images or when the expense of multiple requests is very high.
请参阅: http://en.wikipedia.org/wiki/Data_URI_scheme
更多阅读:
- Dynamically从BLOB条目ASP.NET 图片:渲染ASP
- 动态图像生成的
- Dynamically Rendering asp:Image from BLOB entry in ASP.NET
- Dynamic Image Generation
这篇关于显示VARBINARY作为一个可下载的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!