通过Flask和html在重定向页面上显示提交的图像[复制]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我正在尝试创建一个接收用户提交的图像的页面,并自动将它们重定向到渲染图像的新页面。我的大部分代码都是从这里借来的:How to pass uploaded image to template.html in Flask。但我似乎无法让它发挥作用;我遇到了400:Bad Request。在我看来,图像不是在/static/images下保存,但我不确定为什么。

以下是index.html的提交表格:

<form method="POST" action="{{ url_for('predict') }}" enctype="multipart/form-data">
    <label for="file-input" class="custom-file-upload">
        <i class="fa fa-cloud-upload"></i> Upload Image
    </label>
    <input name="image-input" id="file-input" type="file" align="center" onchange="this.form.submit();">
</form>

这是我的app.py代码:

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

UPLOAD_FOLDER = '/static/images/'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'tiff'])

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

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/predict/', methods=['POST', 'GET'])
def predict():
    if request.method == 'POST':
        file = request.files['file']
        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('uploaded_file', filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/show/<filename>')
def uploaded_file(filename):
    return render_template('classify.html', filename=filename)

@app.route('/uploads/<filename>')
def send_file(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)


if __name__ == '__main__':
    app.run(debug=True)

最后,我尝试使用以下代码在classify.html中呈现它:

  {% if filename %}
  <h1>some text<img src="{{ url_for('send_file', filename=filename) }}"> more text!</h1>
  {% else %}
  <h1>no image for whatever reason</h1>
  {% endif %}

我在哪里错了?

python html forms flask request
1个回答
0
投票

看起来我在输入中错过了一个参数:name=file中的index.html。添加修复错误。总而言之,输入行看起来像这样:

<input id="file-input" name=file type="file" align="center" onchange="this.form.submit();">

© www.soinside.com 2019 - 2024. All rights reserved.