python - flask redirect 重定向问题?
phpcn_u1582
phpcn_u1582 2017-05-18 10:48:50
0
1
796

代码如下, 图片能上传成功, 但是图片上传成功后不能显示图片, 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)

但之前的思路不对的么?

phpcn_u1582
phpcn_u1582

全部回复(1)
滿天的星座

对于图片的显示,需要定义1个路由用于发送静态文件,可以使用send_from_directory来进行对应的处理。

@app.route('/get_media/<path:filename>', methods=['GET'])
def get_media(filename):
   return send_from_directory('/media/', filename)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!