我正在尝试从我的 Amazon S3 存储桶加载远程图像并将其以二进制形式发送到浏览器。我同时也在尝试学习ASP.Net。多年来我一直是一个典型的程序员,需要改变。我昨天开始,今天第一次头痛。
在我的应用程序的页面上,我有这个图像元素:
<img src="loadImage.ashx?p=rqrewrwr">
在 loadImage.ashx 上,我有这个确切的代码:
-------------------------------------------------
<%@ WebHandler Language="C#" Class="Handler" %>
string url = "https://............10000.JPG";
byte[] imageData;
using (WebClient client = new WebClient()) {
imageData = client.DownloadData(url);
}
public void ProcessRequest(HttpContext context)
{
context.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
-------------------------------------------------
这可能有很多错误,因为这是我第一次尝试 .net,并且不知道我在做什么。首先,我收到以下错误,但肯定还有更多错误。
CS0116: A namespace does not directly contain members such as fields or methods
这是第 3 行,即 string url = "https://............"
最佳答案
对于 HttpHandler,您必须将代码放在代码后面...如果您在解决方案资源管理器中展开 loadimage.ashx,您应该会看到一个 loadimage.ashx.cs 文件。该文件是您的逻辑所在的位置,并且所有逻辑都应位于 ProcessRequest 方法中。
所以loadimage.ashx应该基本上是空的:
<%@ WebHandler Language="C#" Class="loadimage" %>
loadimage.ashx.cs 应该包含其余部分:
using System.Web;
public class loadimage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string url = "https://............10000.JPG";
byte[] imageData;
using (WebClient client = new WebClient())
{
imageData = client.DownloadData(url);
}
context.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
public bool IsReusable
{
get { return false; }
}
}
或者,您可以创建一个提供图像的 aspx 页面。这消除了需求背后的代码,但增加了一点开销...使用以下内容创建一个 loadimage.aspx 页面:
<%@ Page Language="C#" AutoEventWireup="true" %>
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
string url = "https://............10000.JPG";
byte[] imageData;
using (System.Net.WebClient client = new System.Net.WebClient())
{
imageData = client.DownloadData(url);
}
Response.ContentType = "image/png"; // Change the content type if necessary
Response.OutputStream.Write(imageData, 0, imageData.Length);
Response.Flush();
Response.End();
}
</script>
然后在图像src中引用这个loadimage.aspx而不是ashx。
关于C# - 使用 .ashx 文件加载远程图像并发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11597389/