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

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

问题描述



我现在将用户上传的照片保存在烧录文件夹以外的目录中(在 openshift ,当前保存在 app-root / data 下的数据文件夹中的镜像, code> app-root / repo / )。

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



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

   -  data / 
|
- 上传/
- 回购/
|
- app /
|
- __init__.py

正如您可以看到flask app文件夹外的数据文件夹。如何从flask app目录生成链接到存储在 data / uploads (上一层)中的文件是个问题?

解决方案

您有 send_from_directory

a> 函数可以实现你想要的功能,我要做的就是用媒体文件所在的路径声明一个名为 MEDIA_FOLDER 的常量,然后,唯一需要做的就是调用这样的函数:

$ p $ from config import MEDIA_FOLDER

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

$ b然后,调用它,你可以这样做:

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

有关th的信息此处


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

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 ?

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

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

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 ?

解决方案

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天全站免登陆