Flask image upload in HTML?

陌路散爱 提交于 2019-12-10 12:24:01

问题


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)

回答1:


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!




回答2:


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



来源:https://stackoverflow.com/questions/31913257/flask-image-upload-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!