我是Flask的新手并尝试加载上传到我服务器中的图片
但是当我尝试加载图片时,我总是得到broken link image
我认为我的代码中有一些错误,但我无法弄清楚它是什么......
Upload.py
import os
from flask import Flask, request, redirect, url_for, send_from_directory,
render_template
from app.forms import image_upload
from app.models import Upload_test
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'files/')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/upload_test', methods=['GET','POST'])
def upload_test():
form = image_upload()
user_id = session['user_id']
if request.method == 'POST':
if form.validate_on_submit():
ext = (form.upload.data.filename).rsplit('.', 1)[1]
filename = secure_filename(form.upload.data.filename + '_' + unicode(uuid.uuid4()) + "." + ext)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
form.upload.data.save(file_path)
image = Upload_test()
image.user_id = user_id
image.filename = filename
db.session.add(image)
db.session.commit()
return redirect(url_for('index', form=form, filename=filename, active_tab='index'))
return render_template("upload_test.html", form=form, active_tab='upload_test')
Upload.py
完美无缺
Load.py
import os
from flask import Flask, request, redirect, url_for, send_from_directory,
render_template
from app.models import Upload_test
@app.route('/upload_test', methods=['GET'])
def upload_test():
if 'logged_in' in session:
user_id = session['user_id']
user = User.query.filter_by(id=user_id).first()
user_image = show_image(user)
return render_template('upload_test.html', user=user, user_image=user_image, active_tab='upload_test')
else:
return redirect(url_for('index'))
def show_image(user):
user_image = db.session.query(Upload_test).filter(Upload_test.user_id == user.id).first()
filename = user_image.filename
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
这是 upload_test.html
的一部分{% if user_image %}
<img src = '{{url_for('upload_test', filename=filname)}}'>
{% endif %}
我认为我在Load.py
或upload_test.html
(或两者兼有)中犯了错误
我哪里错了,如何正确显示图像?