每次我将照片上传到files
文件夹中时,页面都不会将其显示到 post.html
模板中。我唯一看到的是broken image icon
. 这是代码。
配置
import os
from dotenv import load_dotenv
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))
class Config(object):
UPLOAD_EXTENSIONS = '.jpg', '.png', '.gif'
UPLOAD_PATH = 'app/static/files'
路线
def validate_image(stream):
header = stream.read(512) # 512 bytes should be enough for a header check
stream.seek(0) # reset stream pointer
format = imghdr.what(None, header)
if not format:
return None
return '.' + (format if format != 'jpeg' else 'jpg')
@bp.route('/photos')
def photos():
files = os.listdir(current_app.config['UPLOAD_PATH'])
return render_template('photos.html', files=files)
@bp.route('/photos', methods=['POST'])
def upload_files():
uploaded_file = request.files['file']
filename = secure_filename(uploaded_file.filename)
if filename != '':
file_ext = os.path.splitext(filename)[1]
if file_ext not in current_app.config['UPLOAD_EXTENSIONS'] or \
file_ext != validate_image(uploaded_file.stream):
abort(400)
uploaded_file.save(os.path.join(current_app.config['UPLOAD_PATH'], filename))
return redirect(url_for('main.photos'))
@bp.route('/uploads/<filename>')
def upload(filename):
return send_from_directory(os.path.join(current_app.config['UPLOAD_PATH'], filename))
HTML
{% extends "base.html" %}
{% block app_content %}
<h1>File Upload</h1>
<form method="POST" action="http://127.0.0.1:5000/photos" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="Submit"></p>
</form>
<hr>
{% for file in files %}
<img src="{{ url_for('main.upload', filename=files) }}" style="width: 125px">
{% endfor %}
{% endblock %}