Thomas Wagenaar
Thomas Wagenaar

Reputation: 6759

How to encode image to send over Python HTTP server?

I would like some help on my following handler:

 class MyHandler(http.server.BaseHTTPRequestHandler):
     def do_HEAD(client):
        client.send_response(200)
        client.send_header("Content-type", "text/html")
        client.end_headers()
     def do_GET(client):
        if client.path == "/":
           client.send_response(200)
           client.send_header("Content-type", "text/html")
           client.end_headers()

           client.wfile.write(load('index.html'))

 def load(file):
    with open(file, 'r') as file:
    return encode(str(file.read()))

 def encode(file):
    return bytes(file, 'UTF-8')

I've got this, the function load() is someone else in the file. Sending a HTML page over my HTTP handler seems to be working, but how can I send an image? How do I need to encode it and what Content-type should I use?

Help is greatly appreciated!

(PS: I would like the image that is send to be seen in the browser if I connect to my httpserver)

Upvotes: 11

Views: 30100

Answers (2)

Juergen
Juergen

Reputation: 12728

For a PNG image you have to set the content-type to "image/png". For jpg: "image/jpeg".

Other Content types can be found here.

Edit: Yes, I forgot about encoding in my first edit.

The answer is: You don't! When you load your image from a file, it is in the correct encoding already.

I read about your codec problem: The problem is, as much I see in your load function. Don't try to encode the file content.

You may use for binary data this:

def load_binary(filename):
    with open(filename, 'rb') as file_handle:
        return file_handle.read()

Upvotes: 14

Liblor
Liblor

Reputation: 500

As mentioned by Juergen you have to set the accordingly content-type. This example I found may help you: https://github.com/tanzilli/playground/blob/master/python/httpserver/example2.py

The example is in Python 2, but the changes should be minor.

Ah and it's better to use self instead of client -> see PEP 8, Python's style guide

Upvotes: 3

Related Questions