Home > Software engineering >  python webserver html don't display image
python webserver html don't display image

Time:11-06

I want to create a little web server. I'm blocking to display an image with the dedicated html block.

There is the code of my web server

from http.server import SimpleHTTPRequestHandler, HTTPServer
import time
import socket
import json
import os
import socketserver

hostName = "127.0.0.1"
serverPort = 8080

class MyServer(SimpleHTTPRequestHandler):
    head = """
    <head lang="fr">
        <title>Title</title>
        <meta charset="utf-8">
    </head>
    """

    navbar = """<nav><a  href="#"><img src="my_img.png"></a></nav>"""

   def index(self):
     print(os.listdir())
     # List the directory -> my_img is present

     self.send_response(200)
     self.send_header("Content-type", "text/html")
     self.end_headers()
     self.wfile.write(bytes(self.head, "utf-8"))
     self.wfile.write(bytes("<body>", "utf-8"))
     self.wfile.write(bytes(self.navbar, "utf-8"))

     p = """
        <div >
            <div >
                <div ></div>
                <div >
                    <h1>Dashboard</h1>
                    <h2>Bienvenue !</h2>
                    <img src="my_img.png">
                </div>
            </div>
        </div>
     """

     self.wfile.write(bytes(p, "utf-8"))
     self.wfile.write(bytes("</body></html>", "utf-8"))

  def do_GET(self):
    if self.path == "/":
        self.index()
    else:
        self.send_response(404)
        self.send_header("Content-type", "text/html")
        self.end_headers()

if __name__ == "__main__":
  webServer = HTTPServer((hostName, serverPort), MyServer)
  print("Server started http://%s:%s" % (hostName, serverPort))

  try:
    webServer.serve_forever()
  except KeyboardInterrupt:
    pass

  webServer.server_close()
  print("Server stopped.")

So the image is not displayed

On the chrome console debugger :

Failed to load resource: the server responded with a status of 404 (Not Found)

I start the web server with this command :

 python3 WebServer.py

In the current directory :

  • WebServer.py
  • my_img.png

CodePudding user response:

Thansk to @diggusbickus,

The part to adapt is int the do_GET function :

def do_GET(self):
    if self.path == "/":
        self.index()
    elif self.path == "/my_img.png":
        imgname = self.path
        imgname = imgname[1:]
        imgfile = open(imgname, 'rb').read()
        mimetype = mimetypes.MimeTypes().guess_type(imgname)[0]
        self.send_response(200)
        self.send_header('Content-type', mimetype)
        self.end_headers()
        self.wfile.write(imgfile)
    else:
        self.send_response(404)
        self.send_header("Content-type", "text/html")
        self.end_headers()

New elif added, the name of the requested image.

Before this, the web page shouldn't displayed this due to the do_GET function too much restricted.

We retrieve the name (remove the first character in the image name -> "/")

We retrieve the mimetype (jpeg/png/...)

And we send the byte of the images.

It fixes my problem, the image is displayed in the web page.

CodePudding user response:

Your Webserver.py works just fine. (tested with firefox/safari/chrome on macos)

the error of

Failed to load resource: the server responded with a status of 404 (Not Found)

arises because the resource you are requesting(say my_img.png) does not exist in the requested path, which is supposed to be displayed following the error message. Taking an example from another question, ref.

Failed to load resource: the server responded with a status of 404 (Not Found) 
/* -here-> */ http://localhost:8080/RetailSmart/jsp/Jquery/style.css

And you should post it too.

In general, encountering such errors is because you compile and launch your script in an IDE (e.g. pycharm), which normally separate the source files (say files under src directory) and build files (say dest/output/build directory). And it necessary to use precise relative path to your resource to make your server can access it correctly.

  • Related