一尘不染

如何在Flask中将上传的图像传递到template.html

flask

我正在使用flask,并尝试使用快速入门教程(仅在我的计算机(本地服务器)上运行)做一些非常简单的事情。我制作了一个简单的上传表单,可以成功上传图像文件。然后,我想将此图像作为变量传递给,template.html以在页面内显示。该template.html文件显示正常,但图像始终为broken link image symbol。我尝试了许多不同的方法,但是我感觉自己做的事情有点错误。

import os
from flask import Flask, request, redirect, url_for, send_from_directory, 
                  render_template

UPLOAD_FOLDER = '/home/me/Desktop/projects/flask/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    filename = 'http://127.0.0.1:5000/uploads/' + filename
    return render_template('template.html', filename = filename)

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

这是template.html:

<!doctype html>
<title>Hello from Flask</title>
{% if filename %}
  <h1>some text<img src="{{filename}}"> more text!</h1>
{% else %}
  <h1>no image for whatever reason</h1>
{% endif %}

如何将上传的图像文件传递到,template.html以便正确显示?


阅读 397

收藏
2020-04-06

共1个答案

一尘不染

现在发生的是/uploads/foo.jpg返回template.html中的HTML。在这里,你尝试/uploads/foo.jpg用作img标签的来源。你无处可提供实际图像。

让我们这样修改它:/show/foo.jpg返回HTML页面并/uploads/foo.jpg返回图像。用这两条替换后一条路线,你应该会很好:

@app.route('/show/<filename>')
def uploaded_file(filename):
    filename = 'http://127.0.0.1:5000/uploads/' + filename
    return render_template('template.html', filename=filename)

@app.route('/uploads/<filename>')
def send_file(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)
2020-04-06