代码如下, 图片能上传成功, 但是图片上传成功后不能显示图片, redirect这样写对么?
#!/usr/bin/env python3
# -*- coding:utf-8-*-
import os
from flask import Flask, render_template, request, redirect, url_for
from flask_uploads import UploadSet, configure_uploads, patch_request_class, IMAGES
app = Flask(__name__)
app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd() + "/upload/img"
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)
@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
file_url = photos.url(filename)
print("filename = %s, file_url = %s" % (filename, file_url))
return redirect(url_for('index', file_url=file_url))
return render_template('index.html', file_url=None)
if __name__ == '__main__':
app.run(port=8080)
<!doctype html>
<html>
<head>
<title>Demo-上传文件</title>
</head>
<body>
<h1>文件上传demo</h1>
<form method="post" enctype="multipart/form-data">
<input type="file" name="photo">
<input type="submit" value="上传">
</form>
<br>
{% if file_url %}
<img src="{{ file_url }}" alt="">
{% else %}
<p>还没有上传文件</p>
{% endif %}
</body>
</html>
----------更新----------
将index路由修改了一下, 达到了想要的效果:
@app.route('/', methods=['POST', 'GET'])
def index():
file_url = None
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
file_url = photos.url(filename)
print("filename = %s, file_url = %s" % (filename, file_url))
return render_template('index.html', file_url=file_url)
但之前的思路不对的么?
对于图片的显示,需要定义1个路由用于发送静态文件,可以使用
send_from_directory
来进行对应的处理。