我正在使用flask,并尝试使用快速入门教程做一些非常简单的事情,只是在我的机器(本地服务器)上运行。我制作了一个简单的上传表单,它成功上传了一个图像文件。然后我想将此图像作为变量传递给 atemplate.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
它以正确显示?
谢谢