Reputation: 43
I'm trying to create an HTTP server with python.
All is working exept the image does not load in Google chrome or Microsoft Edge using localhost:{port}.
There is the code :
import socket
import time
http_head = "HTTP/1.1 200 OK\r\n"
http_head += "Date:"+ time.asctime() +"GMT\r\n"
http_head += "Expires: -1\r\n"
http_head += "Cache-Control: private, max-age=0\r\n"
http_head += "Content-Type: text/html;"
http_head += "charset=utf-8\r\n"
http_head += "\r\n"
data = "<html><head><meta charset='utf-8'/></head>"
data += "<body><h1>In321 is the best course ! (doubt) </h1>"
data += "\r\n"
data += "<img src=\"C:\\Users\\aliel\\OneDrive\\Documents\\GitHub\\TP2_In321\\crying_cat_with_thumb_up.jpg\" alt=\"A crying cat with thumb up\">"
data += "</body></html>\r\n"
data += "\r\n"
http_response = http_head.encode("ascii") + data.encode("utf-8")
TCP_IP = '127.0.0.1'
TCP_PORT = 55000
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT)) # Demande à l’OS d’associer la socket à une ip/port
s.listen(1) # transforme la socket en socket de connexion
print(" Waiting client… ")
scom, caddr = s.accept()
print("client connected with address : ", caddr)
data = scom.recv(BUFFER_SIZE)
print("received data:", data.decode('utf-8'))
scom.send(http_response)
s.close()
scom.close()
Upvotes: 1
Views: 1644
Reputation: 2004
The problem is since you're using a string, the browser after loading the HTML content tries to load the image but then notices that you're trying to read a local file and hence blocks the request. (If you right click the image and click copy image address you can see it says "about:blank#blocked"
). The way you can circumvent this is either by Creating an HTML file or embedding the image as bytes in the string itself.
You can do that as follows
import base64
with open(path,"rb") as i:
encoded_string = base64.b64encode(i.read()).decode( 'utf-8' )
and adding the following to your image source (where path
is the path to your image)
data += f'<img src="data:image/png;base64, {encoded_string}">'
Upvotes: 2