用户登录
用户注册

分享至

在 C# 代理中从 Web 服务器读取图像

  • 作者: 朕就静静的看你装逼
  • 来源: 51数据库
  • 2023-02-13

问题描述

我正在尝试编写一个代理,该代理从一台服务器读取图像并将其返回给提供的 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 标签的 source 属性中访问它.将内容类型设置为 application/octet-stream 提示保存文件并将其设置为 image/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,它是一个 Text读者!

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);
        }
    }
}
软件
前端设计
程序设计
Java相关