我如何链接到不在烧瓶静态文件夹中的图像 [英] How do i link to images not in Static folder in flask

查看:24
本文介绍了我如何链接到不在烧瓶静态文件夹中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在flask中,如何提供不在静态文件夹中的图像?

In flask, how do I serve images that are not in the static folder?

我目前将用户上传的照片保存在烧瓶文件夹之外的目录中(在 openshift 上,图像当前保存在 app-root/data 下的数据文件夹中并且烧瓶文件在 app-root/repo/).

I currently save the user uploaded photos on a directory that is outside the flask folder (On openshift, image currently saving in the data folder under app-root/data and the flask files are in app-root/repo/).

在我的模板中,我如何提供图像文件?

In my templates, how do i serve the image files ?

使用url_for,我如何引用flask 文件夹之外的这些图像文件?

Using url_for, how do i reference these image files that are outside the flask folder?

- data/
 |
  -- uploads/
- repo/
 |
  -- app/
    |
     -- __init__.py

如您所见,flask 应用程序文件夹外的数据文件夹.我如何从烧瓶应用程序目录生成存储在 data/uploads(上一级)中的文件的链接是问题?

As you can see the data folder outside the flask app folder. How do i generate links to files stored in data/uploads (one level up) from the flask app directory is the question ?

推荐答案

您拥有 send_from_directory 函数可以执行您想要的操作,我要做的是声明一个名为 MEDIA_FOLDER 的常量,其中包含媒体文件所在的路径和然后,您唯一需要做的就是像这样调用函数:

You have the send_from_directory function that does what you want, what I would do is declare a constant called MEDIA_FOLDER with the path where the media files are located and then, the only thing you need to do is to call the function like this:

from config import MEDIA_FOLDER

@app.route('/uploads/<path:filename>')
def download_file(filename):
    return send_from_directory(MEDIA_FOLDER, filename, as_attachment=True)

然后,要调用它,您只需执行以下操作:

Then, to invoke it, you just do this:

{{ url_for('download_file', filename='dogs.jpg') }}

您可以在这里获得更多信息.

You can have more info about this here.

这篇关于我如何链接到不在烧瓶静态文件夹中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆