如何使用Python Flask使用从HTML网页上传的图像

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

我正在尝试创建一个图像识别程序,到目前为止我已经制作了模型和所有实际的人工智能方面的东西。然而,当我在网站中实现这一点时,当我尝试使用 Python Flask 在另一个网页上显示预测时,遇到了很多意想不到的麻烦。

例如,每当我在选择图像后单击上传时,它只会打开一个新网页,其中包含图像和项目文件的目录,我可以在其中导航文件/文件夹。它应该只是一个包含预测和一些文本的容器。

我对这种编程风格很陌生,所以我现在不确定如何解决这些错误,所以任何帮助将不胜感激。我已经链接了当前项目目录结构的照片。

enter image description here

这是我的 Python Flask 代码

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

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        return redirect(request.url)
    if file:
        # Save the file
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(file_path)
        # Redirect to the prediction page
        return redirect(url_for('predict', filename=file.filename))

@app.route('/predict/<filename>')
def predict(filename):
    # Load your model and make a prediction
    result = model.predict(os.path.join(app.config['UPLOAD_FOLDER'], filename))  # Replace with your prediction logic
    return render_template('results.html', prediction=result, filename=filename)

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

这是我的结果 html 代码:

    <div class="container">
        <h1>Prediction Result: {{ prediction }}</h1>
        <img src="{{ url_for('static', filename='uploads/' + filename) }}" alt="Uploaded Mole Image" width="300px">
        <br>

如果有必要,这是我的上传表格:

            <form action = "../static/uploads/" method = "post" enctype = "multipart/form-data">
                <input type = "file" name = "file" accept = "image/*" required>
                <button type = "submit">Upload</button>
            </form>
python html forms flask upload
1个回答
0
投票

您可以执行以下操作:-

从表单中删除

action
并添加
onsubmit
,您可以在其中处理上传逻辑。这将使您的页面保持在同一选项卡中并将您的图像发布到后端。

function submitHandler(e) {
 e.preventDefault();
 // Code to manage file upload
}

<form action="" onsubmit="submitHandler()/>
© www.soinside.com 2019 - 2024. All rights reserved.