Reading Image from Web Server in C# proxy

后端 未结 4 1239
粉色の甜心
粉色の甜心 2020-12-21 03:49

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.

I am tryin

4条回答
  •  情歌与酒
    2020-12-21 04:16

    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);
            }
        }
    }
    

提交回复
热议问题