阅读来自Web服务器的图像在C#代理
我想写一个代理服务器从一台服务器读取图像并将其返回到提供的HttpContext的,但我刚开字符流回来。
I am trying to write a proxy which reads an image from one server and returns it to the HttpContext supplied, but I am just getting character stream back.
我正尝试以下操作:
WebRequest req = WebRequest.Create(image);
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter (context.Response.OutputStream);
sw.Write (sr.ReadToEnd());
但正如我前面提到的,这只是文本响应。
But as I mentioned earlier, this is just responding with text.
我如何告诉它是一个形象
How do I tell it that it is an image?
编辑:我从一个网页内的源属性访问该img标签。内容类型设置为应用程序/八位字节流提示保存文件,并将其设置为图像/ JPEG只是文件名进行响应。我要的是要返回,并通过调用页面显示的图像。
I am accessing this from within a web page in the source attribute of an img tag. Setting the content type to application/octet-stream prompts to save the file and setting it to image/jpeg just responds with the filename. What I want is the image to be returned and displayed by the calling page.
由于您使用的二进制工作,你不不想使用的StreamReader
,这是一个文字阅读器!
Since you are working with binary, you don't want to use StreamReader
, which is a TextReader!
现在,假设你已经正确设置的内容类型,你应该只使用响应流:
Now, assuming that you've set the content-type correctly, you should just use the response stream:
const int BUFFER_SIZE = 1024 * 1024;
var req = WebRequest.Create(imageUrl);
using (var resp = req.GetResponse())
{
using (var stream = resp.GetResponseStream())
{
var bytes = new byte[BUFFER_SIZE];
while (true)
{
var n = stream.Read(bytes, 0, BUFFER_SIZE);
if (n == 0)
{
break;
}
context.Response.OutputStream.Write(bytes, 0, n);
}
}
}