zeinab sohrabpour
zeinab sohrabpour

Reputation: 11

Flask image upload in HTML?

So, I wanted to upload an image in my website(HTML). The box does show up when I run the code but it does not show the image, instead it shows the image name. This is the code I used: app = Flask(name)

<img src="{{ url_for('static', filename='image.jpg') }}" alt="image.jpg" width=208 length=284>

I did try putting my image and code in the directory : /html/static

I even tried a code as simple as this but it didn't work:

from flask import Flask
app = Flask(__name__)

@app.route('/new')
def new_file():
    return """

<html>
<head>
</head>
<body>
<p>
This is an image.
<img src="{{ url_for('static', filename='image.jpg') }}" alt="image.jpg"     width=208 length=284>
</p>
</body>
</html>"""

if __name__=='__main__':
    app.run(host='0.0.0.0', debug=True)

Upvotes: 0

Views: 1585

Answers (2)

Anuj
Anuj

Reputation: 7067

The issue is that the static folder which you are using in url_for should be there within your application folder and not some separate folder in something like /html/static

I have been following the application structure from Miguel Grinberg Flask Blog:

Your Application\
  app\
    static\
    templates\
    __init__.py
    views.py
    routes.py
  manage.py

Your image should be inside the app/static folder so that its url can be automatically generated by using url_for.

Also, make sure to use single quotes around the image name, if double quotes have been used outside. You can refer to:

Having both single and double quotation in a python string

Upvotes: 0

sunaurus
sunaurus

Reputation: 64

I am assuming that the img tag is properly in a template and that the app = Flask(__name__) is NOT in a template, you just copied them both into the example?

It looks like you have a problem with quotation marks. Essentially, you shouldn't use double-quotes "inside" a double-quote string. Here's an example with the mistake: "This is "the" wrong method". Here's an example without the mistake: "This is 'the' correct method." Notice I've replaced the double-quotes inside the string with single-quotes.

Here's how you would apply it to your code:

<img src="{{ url_for('static', filename='image.jpg') }}" alt="image.jpg" width=208 length=284>

I've replaced the double quotation marks around the filename with single quotation marks. Let me know if that helps!

Upvotes: 1

Related Questions