简体   繁体   English

如何重定向到 flask 上的上一页?

[英]How can I redirect to previous page on flask?

I'm at a beginner's level with flask and am trying to create a web app.我对 flask 处于初学者水平,并且正在尝试创建 web 应用程序。 The user will upload a photo from the file explorer and the image is displayed on screen (thanks to an answer I found here ).用户将从文件资源管理器中上传照片,并且图像会显示在屏幕上(感谢我在此处找到的答案)。

My issue is that when I click "go back" when I'm at the confirmation page, I want to redirect to the file upload page ( http://127.0.0.1:5000/upload ) but it seems to not work at all.我的问题是,当我在确认页面单击“返回”时,我想重定向到文件上传页面( http://127.0.0.1:5000/upload )但它似乎根本不起作用. The url changes but the page is still at the /uploadconfirmation page that asks user if they want to proceed. url 发生变化,但页面仍在 /uploadconfirmation 页面,询问用户是否要继续。 I'm not sure if it's due to the code I found that displays the image or not.我不确定这是否是由于我发现显示图像的代码所致。

Any help is appreciated!任何帮助表示赞赏!

Images:图片: /上传确认页面 单击“返回”时

Code:代码:

main.py主文件

import os
from flask import Flask, flash, request, redirect, url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'C:/Users/yurik/OneDrive/FYPCode/code+images/FullProject/imagesUploaded'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)

app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# specifies max file size = 16MB
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# HOME:
#index method,returns index.html
@app.route('/home')
def index():                             
    return render_template('index.html')

# UPLOAD FILE:  
@app.route('/upload')
def upload_page():
    return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No file selected for uploading')
            return redirect(request.url)
        # file is uploaded to imagesUploaded folder in FullProject
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('file_confirm', filename=filename))
        else:
            flash('Allowed file types are png, jpg, jpeg, gif')
            return redirect(request.url)

# FILE CONFIRMATION/show file uploaded:
# Returns html page
@app.route('/show/<filename>')
def file_confirm(filename):
    filename = 'http://127.0.0.1:5000/uploadconfirmation/' + filename
    return render_template('uploadconfirmation.html', filename=filename)

# returns image
@app.route('/uploadconfirmation/<filename>')
def show_file(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)

# run flask app and .py file
if __name__ == '__main__':
    app.run()

upload.html上传.html

<!DOCTYPE html>
<html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <head>
        <link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
        <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
        <meta charset=utf-8 />

        <title>File Upload </title>
        <link rel="stylesheet" href="{{url_for('static', filename='style.css')}}">
    </head>
    <body>
        <div class="maintitle">
            <h1 class="heading">Select a file to upload</h1>    
        </div>
        <div class="uploadbody">
            <p>
                {% with messages = get_flashed_messages() %}
                    {% if messages %}
                        <ul class=flashes>
                          {% for message in messages %}
                              <li>{{ message }}</li>
                          {% endfor %}
                        </ul>
                    {% endif %}
                {% endwith %}
            </p>
            <form method="post" action="/" enctype="multipart/form-data">
                <dl>
                    <p>
                        <input type="file" name="file" autocomplete="off" required>
                    </p>
                </dl>
                <p>
                    <input type="submit" class="submit "value="Submit">
                </p>
            </form>
    </body>
</html>

uploadconfirmation.html上传确认.html

<!DOCTYPE html>
<html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <head>
        <title>File Confirmation </title>
        <link rel="stylesheet" href="{{url_for('static', filename='style.css')}}">
    </head>
    <body>
        <div class="maintitle">
            <h2 class="proceedheading">Do you want to proceed with this image?</h2>    
        </div>
        <div class="uploadbody">
            <p>
                {% if filename %}
                    <img src="{{filename}}" width="80%" height="80%">
                {% else %}
                    <h1>no image for whatever reason</h1>
                {% endif %}
                <a href="upload" class="upload" value="upload">Go back</a> 
                <a href="choosebrand" class="upload" value="choosebrand">Yes</a>
        </div>
    </body>
</html>

Try to render link dynamically in the template:尝试在模板中动态呈现链接:

<a href="{{ url_for('upload') }}">Go back</a>

If you want to be able to go back, use the following code:如果您希望能够将 go 退回,请使用以下代码:

#base.html (this code should be in every template)
window.onload=function(){localStorage.setItem("prev_page", location.href)}

function go_back(){window.location.href = localStorage.getItem("prev_page")};

The following code will allow you to have a back button.以下代码将允许您有一个后退按钮。

You can use the url_for method by flask to get the url of the upload page.可以使用flask的url_for方法获取上传页面的url。

<a href="{{ url_for('upload_page') }}">Back</a>

Note: url_for takes the route method name as the parameter ie 'upload_page' instead of 'upload'.注意:url_for 将路由方法名称作为参数,即'upload_page' 而不是'upload'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM