The code is as follows. The picture can be uploaded successfully, but the picture cannot be displayed after the picture is uploaded successfully. Is this the correct way to write 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>
----------Update----------
Modified the index routing and achieved the desired effect:
@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)
But was the previous thinking wrong?
For image display, you need to define a route for sending static files, and you can use
send_from_directory
for corresponding processing.