2012-07-22 52 views
2

我試圖從我的Amazon S3存儲區加載遠程圖像,並以二進制形式將其發送到瀏覽器。我也試圖在同一時間學習ASP.Net。我一直是一個經典的程序員多年,需要改變。我昨天開始了,今天頭痛了。C# - 使用.ashx文件加載遠程圖像併發送到瀏覽器

在我的應用我有這樣的圖像元素的網頁:

<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://............"

回答

5

對於一個HttpHandler,你必須把代碼後面的代碼......如果展開在Solution Explorer 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而不是ASHX引用此loadimage.aspx。

+0

我沒有使用VS或解決方案資源管理器,我應該這樣說。我能在Dreamweaver中創建一個新文件loadImage.ashx.cs嗎? – TheCarver 2012-07-22 03:23:37

+0

我剛剛創建了一個新頁面loadImage.ashx.cs,並且出現了一個新錯誤:「無法創建類型'處理程序'。」 – TheCarver 2012-07-22 03:26:44

+0

我對Dreamweaver並不熟悉,但我相信您將不得不在處理請求的.cs文件中創建一個類。 ashx文件中的Class屬性聲明必須指向完全限定的類名(名稱空間和類名)。 – 2012-07-22 03:34:11

相關問題