Как я могу перенаправить на предыдущую страницу на flask? - PullRequest
0 голосов
/ 07 апреля 2020

Я на начальном уровне с flask и пытаюсь создать веб-приложение. Пользователь загрузит фотографию из проводника, и изображение отобразится на экране (благодаря ответу, который я нашел здесь ).

Моя проблема в том, что когда я нажимаю "go back", когда я на странице подтверждения, я хочу перенаправить на страницу загрузки файла (http://127.0.0.1: 5000 / upload ) но, похоже, не работает вообще. URL изменяется, но страница все еще находится на странице / uploadconfirmation, которая спрашивает пользователя, хотят ли они продолжить. Я не уверен, что из-за кода, который я нашел, отображается изображение.

Любая помощь приветствуется!

Изображения: /uploadconfirmation page when

Код:

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

<!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

<!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>

Ответы [ 2 ]

0 голосов
/ 07 апреля 2020

Если вы хотите иметь возможность 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")};

Следующий код позволит вам иметь кнопку возврата.

0 голосов
/ 07 апреля 2020

Попробуйте динамически отобразить ссылку в шаблоне:

<a href="{{ url_for('upload') }}">Go back</a>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...