python - flask redirect 重定向問題?
問題描述
代碼如下, 圖片能上傳成功, 但是圖片上傳成功后不能顯示圖片, redirect這樣寫對么?
#!/usr/bin/env python3# -*- coding:utf-8-*-import osfrom flask import Flask, render_template, request, redirect, url_forfrom flask_uploads import UploadSet, configure_uploads, patch_request_class, IMAGESapp = 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='http://m.cgvv.com.cn/wenda/{{ 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:對于圖片的顯示,需要定義1個路由用于發(fā)送靜態(tài)文件,可以使用send_from_directory來進行對應(yīng)的處理。
@app.route(’/get_media/<path:filename>’, methods=[’GET’])def get_media(filename): return send_from_directory(’/media/’, filename)
相關(guān)文章:
1. windows誤人子弟啊2. mysql優(yōu)化 - MySQL如何為配置表建立索引?3. 我在網(wǎng)址中輸入localhost/abc.php顯示的是not found是為什么呢?4. 關(guān)于mysql聯(lián)合查詢一對多的顯示結(jié)果問題5. 如何用筆記本上的apache做微信開發(fā)的服務(wù)器6. 實現(xiàn)bing搜索工具urlAPI提交7. 數(shù)據(jù)庫 - Mysql的存儲過程真的是個坑!求助下面的存儲過程哪里錯啦,實在是找不到哪里的問題了。8. python - linux怎么在每天的凌晨2點執(zhí)行一次這個log.py文件9. MySQL主鍵沖突時的更新操作和替換操作在功能上有什么差別(如圖)10. 冒昧問一下,我這php代碼哪里出錯了???
