[Python] How To Display Image to HTML using python

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    To display image from the path specified to the HTML browser in python. I have coded in this manner.

    index.html

    <html>
    <body>
    <form enctype = "multipart/form-data"
    action = "save_file.py" method = "post">
    <p>File: <input type = "file" name = "filename" /></p>
    <p><input type = "submit" value = "Upload" /></p>
    </form>
    </body>
    </html>


    save_file.py

    #!C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/python.exe

    import cgi, os
    import cgitb; cgitb.enable()
    from PIL import Image

    form = cgi.FieldStorage()

    # Get filename here.
    fileitem = form['filename']

    # Test if the file was uploaded
    if fileitem.filename:
    # strip leading path from file name to avoid
    # directory traversal attacks
    fn = os.path.basename(fileitem.filename)
    open('C:/Apache24/htdocs/tmp/' + fn, 'wb').write(fileitem.file.read())

    message = 'The file "' + fn + '" was uploaded successfully'
    path = 'C:/Apache24/htdocs/tmp/' + fn
    image = Image.open('C:/Apache24/htdocs/tmp/' + fn)
    image.show()
    else:
    message = 'No file was uploaded'
    #Content-Type: text/html\n
    print ("""\
    Content-Type: image/jpg\n
    <!DOCTYPE html>
    <html>
    <body>
    <p>%s </p>
    <img src="%s" alt="C:/Apache24/htdocs/tmp/%s">
    </body>
    </html>
    """ % (message,path,fn,))



    Expected Output: It should display image taking from that path specified.

    Actual Output: Display with img block with text C:/Apache24/htdocs/tmp/xy.jpg

    Continue reading...

Compartilhe esta Página