Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

http - Reading Image from Web Server in C# proxy

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 trying the following:

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?

Edit: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...