使用Flask app引用用户提供的文件

时间:2016-12-24 03:49:21

标签: python image flask jinja2

我是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>

1 个答案:

答案 0 :(得分: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 %}