Flask应用程序:HTML未呈现图像

huangapple go评论73阅读模式
英文:

Flask Application: HTML isn't rendering image

问题

我正在尝试引用位于我的本地文件系统中的图像。我不确定是否正确引用了它。我曾看到其他来源在路径前使用了'file://'标识。

英文:

I'm trying to reference an image that is in my local file system. I'm not sure if I'm referencing it correctly. I've seen other sources use the 'file://' designation before the path.

<html>
    <head>
        <title>title</title>
        <link rel="stylesheet" href="styles.css">
    </head>
   <body>
    <header>
        <nav>
            <ul>
                <li><a href="#about">About</a></li>
                <li><a href="#services">Services</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
        </nav>
    </header>

    <header>
        <h1>Welcome to our Startup</h1>
        <p>Discover the future with us.</p>
        <a href="/about">Learn More</a>
    </header>
    <div id="image">
        <img src="/Users/myname/Flask_App/Images/Komodo_image.jpeg">
    </div>
      
   </body>
</html>

答案1

得分: 1

不要一个系统文件路径,因为这可能会引发跨域错误,而是使用Flask内置的静态文件服务系统。

在你的应用程序目录中创建一个名为static的文件夹:

项目根目录
|___ templates
|    |___ image.jpeg
|___ myapp.py

现在修改你的HTML,将这一行代码替换为:

<img src="{{ url_for('static', filename='image.jpeg') }}">

[未经测试,但应该可以工作]

要了解更多关于Flask和静态文件的信息,请参阅:https://flask.palletsprojects.com/en/2.3.x/tutorial/static/

英文:

Instead of a system file path, which can cause CORS errors, use Flask's built-in static file serving system

Create a folder in your app's directory called static:

project root
|___ templates
|    |___ image.jpeg
|___ myapp.py

Now modify your html, replacing the line

<img src="/Users/myname/Flask_App/Images/Komodo_image.jpeg">

with

<img src="{{ url_for('static', filename='image.jpeg') }}">

[Untested, but should work]

For more on Flask and static files see: https://flask.palletsprojects.com/en/2.3.x/tutorial/static/

huangapple
  • 本文由 发表于 2023年5月29日 08:50:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354121.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定