使用Flask时图片未上传(点击上传时显示未选中文件)。IDE显示302

0 投票
2 回答
39 浏览
提问于 2025-04-14 17:59

我正在学习Flask,想写一段代码来检测图片的边缘,并让用户上传图片。可是我觉得我上传图片的功能有问题,每次点击上传时都显示“没有选择文件”。这是我的代码。

import os.path
from io import BytesIO
from tempfile import mkdtemp

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

from edge_new import edge_detector
from flask_app import UPLOAD_FOLDER

app = Flask(__name__)
app.secret_key = 'sib'

temp_dir = mkdtemp()
app.config[UPLOAD_FOLDER] = 'temp_dir'


@app.route('/')
def hello():
    return "The app is up and running. Go to /edge for functionality"


@app.route('/edge', methods=['POST', 'GET'])
def process_img():
    """
    Function takes an image,
    finds edges in the image,
    returns processed image for download.
    """
    if request.method == 'POST':

        # Check if image exists
        if 'img' not in request.files:
            flash("Image not found"), 400
            return redirect('/edge')

        image = request.files['img']

        # Check if image selected

        if image.filename == "":
            flash("No selected image"), 400
            return redirect('/edge')

        # Save the image

        image_path = secure_filename(image.filename)
        path = os.path.join(temp_dir, image_path)
        image.save(path)

        # Find edges in the image using edge_detector function

        processed_image = edge_detector(path)  # processed_img is ndarray

        # Save the processed image

        
        send_file(BytesIO(processed_image), download_name='processed.jpg', mimetype='image/jpg', as_attachment=True)
        
    return render_template('index.html')




if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000, debug=True)

我尝试了很多方法,但错误依然存在。我试过send_file()、send_from_directory()和cv2.imwrite(),但我不确定哪个有效。这是我的index.html的代码。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload Example</title>
    <style>
    .ok{

        font-size: 20px;
    }
    .op{
        font-size: 20px;
        margin-left: -70px;
        font-weight: bold;
        background-color: yellow;
        border-radius: 5px;
        cursor: pointer;
    }


    </style>
</head>
<body>
    <div class="center">
        <h1> Uploading and Returning Files With a Database in Flask </h1>
        <form method="POST" action="/edge" enctype="multipart/form-data">
            <input class="ok" type="file" name="file">
            <button class="op">Submit</button>
        </form>
    </div>

</body>
</html>

2 个回答

0

我运行了你的代码,检查了一下。

你的接口 /edge 在判断条件和代码块中试图获取img

if 'img' not in request.files:
    flash("Image not found"), 400
    return redirect('/edge')

image = request.files['img']

而你发送的文件是用 name="file" 来表示的。

<input class="ok" type="file" name="file">

你可以通过更新 index.html 中的输入代码来修正这个问题:
(把 name="file" 改成 name="img")

<input class="ok" type="file" name="img">
0

你可以通过输入框的名字来获取它的值。不过,问题是你在输入框的属性里把它设置成了 file,而你却在请求 request.files 里的 img。你要么把 HTML 代码里的属性改成 img,要么在服务器那边请求 file

撰写回答