Dario Benevento
Dario Benevento

Reputation: 47

Webserver response for image in C#

I'm trying to develop a little program in C# as UWP that will be able to send a response over http as HTML page. Actually I'm able to answer with a text stream with this code:

using (var output = args.Socket.OutputStream)
 {
    using (var response = output.AsStreamForWrite())
    {
        var html = Encoding.UTF8.GetBytes(htmlResponse);
        using (var bodyStream = new MemoryStream(html))
        {
            var header = $"HTTP/1.1 200 OK\r\nContent-Length: {bodyStream.Length}\r\nConnection: close\r\n\r\n";
            var headerArray = Encoding.UTF8.GetBytes(header);
            await response.WriteAsync(headerArray, 0, headerArray.Length);
            await bodyStream.CopyToAsync(response);
            await response.FlushAsync();
        }
    }
 }

And the response is

HTTP/1.1 200 OK
Content-Length: {bodyStream.Length}
Connection: close

But when I try to answer with a jpeg image or png image, the answer is not interpreted from browser. I tryed to convert the image in byte array, stream, Base64 but nothing will do the job. How can I do that?

Thanx a lot

Upvotes: 0

Views: 191

Answers (2)

mortb
mortb

Reputation: 9869

You need to set response.ContentType="image/jpeg" or response.ContentType="image/png". Otherwise the browser does not know how to render the image

Upvotes: 1

RokumDev
RokumDev

Reputation: 367

I think you only need to add a header with the mime type: image/jpeg and try to response with the types you listed above.(byte array, stream, Base64)

Upvotes: 0

Related Questions