【问题标题】:Reference user supplied file with Flask app使用 Flask 应用程序参考用户提供的文件
【发布时间】:2016-12-24 03:49:21
【问题描述】:

我一般是 Flask 和 Web 应用程序的新手。我有可能位于不同位置的图像:

-directory1
  -image1
-directory2
  -subdirectory
    -image2
-directory3
  -flask_app
    -app.py
    -static

应用程序的目的是动态地提供对其他目录中的内容的访问,这些目录不是静态的,并且可能会因每个用户而变化。内容无法移动或修改。

如何在不根据用户输入值移动或修改应用程序内其他目录的图像的情况下显示它们?

到目前为止,我有以下内容,但图片链接已损坏:

from flask import Flask, render_template, request, send_from_directory

current_filepath = /directory2/image{}.png

app = Flask(__name__, static_url_path='')

@app.route('/js/<path:filename>')
def download_file(filename):
    return send_from_directory('js', filename)


@app.route('/', methods=['GET','POST'])
def print_form():
    if request.method == 'POST':
        test = current_filepath.format(request.form['image_num'])
        return render_template('form.html', result=test)

    if request.method == 'GET':
        return render_template('form.html')


if __name__ == '__main__':
    app.run(debug=True)

使用以下form.html 文件:

<!DOCTYPE html>
<html lang="en">

<body>
<form method="POST" action=".">
   <input id="post_form_id" name="image_num" value="" />
   <input type="submit">
</form>

{% if result %}
    {{ url_for('download_file', filename= result) }}
    <img src={{ url_for('download_file', filename= result) }}>
{% endif %}

</body>
</html>

【问题讨论】:

    标签: python image flask jinja2


    【解决方案1】:
    app/
       app.py
       ...
    uploads/
       dir1/
          img1.png
          ...   
    ...
    app.config['UPLOAD_FOLDER'] = 'path/to/uploads/dir1'
    
    @app.route('/file/<path:filename>')
    def img_file(filename):
        filename = filename + '.png'
        return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        filename = None
        if request.method == 'POST':
            filename = request.form['img_num']
        return render_template('form.html', filename=filename)
    

    <form method="post" action="" >
        <input type="text" id="form_id" name="img_num">
        <input type="submit" value="submit">
    </form>
        {% if filename %}
        <img src=" {{ url_for('img_file', filename=filename) }}">
        {% endif %}
    

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2011-05-11
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多