程式碼如下, 圖片能上傳成功, 但是圖片上傳成功後不能顯示圖片, 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)
但之前的思路不對的麼?
滿天的星座2017-05-18 10:50:50
對於圖片的顯示,需要定義1個路由用於發送靜態檔案,可以使用send_from_directory
來進行對應的處理。
@app.route('/get_media/<path:filename>', methods=['GET'])
def get_media(filename):
return send_from_directory('/media/', filename)