# 查看图片 @app.route("/photo/<imageId>.jpg") 不知道具体文件夹如何访问
时间: 2024-02-25 17:53:54 浏览: 16
在 Flask 应用中,如果你想要访问指定文件夹下的图片,需要在路由中指定该文件夹的路径。具体步骤如下:
1. 首先,导入 `os` 模块,该模块提供了访问文件系统的函数和方法:
```python
import os
```
2. 然后,在路由中指定要访问的图片路径。假设你的图片都存储在 `/path/to/images` 目录下,你可以在路由中使用 `<path:image_path>` 参数来接收图片的路径:
```python
@app.route("/photo/<path:image_path>")
def photo(image_path):
full_path = os.path.join('/path/to/images', image_path)
if os.path.exists(full_path):
return send_file(full_path, mimetype='image/jpeg')
else:
abort(404)
```
这里使用 `os.path.join()` 方法将 `/path/to/images` 和 `<path:image_path>` 拼接成完整的图片路径,并使用 `os.path.exists()` 方法检查该文件是否存在。如果文件存在,使用 `send_file()` 方法将文件发送给客户端;否则,返回 404 错误。
3. 最后,在 HTML 模板中使用图片路径来访问图片:
```html
<img src="{{ url_for('photo', image_path='example.jpg') }}">
```
这里使用 `url_for()` 方法生成图片的 URL,其中 `image_path` 参数指定图片的路径。
希望这能帮助你访问指定文件夹下的图片。