Reading image from web server in c # proxy

I am trying to write a proxy server that reads an image from one server and returns it to the provided HttpContext, but I just return a stream of characters.

I am trying to do 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 an answer with text.

How can I say this image?

Edit: I am accessing this from inside the webpage in the original attribute of the img tag. Setting the content type to the application / octet stream prompt to save the file and attach it to the image / jpeg simply responds to the file name. I want the image to be returned and displayed by the calling page.

+3
source share
4 answers

, StreamReader, Text Reader!

, , , :

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

. , :

// specify that the response is a JPEG
// Also could use "image/GIF" or "image/PNG" depending on what you're
// getting from the server
Response.ContentType = "image/JPEG";
+1

, ContentType, WebResponse.

 if (resp.ContentType.StartsWith("image/"))
 {
   // Do your stuff
 }
+1

. URL- (URL- ).

try
{
    if (ContentUrl != "")
    {
        string imgExtension = ContentUrl.Substring(ContentUrl.Length - 3, 3);
        switch (imgExtension)
        {
            case "":
                //image/bmp
                Response.ContentType = "image/bmp";
                break;

            case "jpg":
                //image/jpeg
                Response.ContentType = "image/jpeg";
                break;

            case "gif":
                //image/gif
                Response.ContentType = "image/gif";
                break;

            default:
                Response.ContentType = "image/jpeg";
                break;
        }

        if (!ContentUrl.StartsWith("http"))
            Response.BinaryWrite(new byte[] { 0 });

        WebClient wc = new WebClient();
        wc.Credentials = System.Net.CredentialCache.DefaultCredentials;
        Byte[] result;
        result = wc.DownloadData(ContentUrl);


        Response.BinaryWrite(result);

    }
}
catch (Exception ex)
{
    Utility.WriteEventError(Utility.EVENTLOG_SOURCE, string.Format("ImageProxy Error... Url:  {0}, Exception: {1}", ContentUrl, ex.ToString()));
}
finally
{
    Response.End();
}
0

Source: https://habr.com/ru/post/1715069/


All Articles