首页 > 解决方案 > Python Flask 未保存到文件夹

问题描述

我正在尝试创建一个 Python/Flask 应用程序,用户在其中将图像保存到本地文件夹。它创建文件夹,我得到“已上传”成功页面,但图像未保存在文件夹中

这是我的 .py 代码

import os
from flask import Flask, render_template, request

app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

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

@app.route("/upload", methods=['GET','POST'])
def upload():
    target = os.path.join(APP_ROOT, 'images/')
    print(target)

    if not os.path.isdir(target):
        os.mkdir(target)

    for file in request.files.getlist("file"):
        print(file)
        filename = file.filename
        destination = "/".join([target, filename])
        print(destination)
        file.save(destination)

    return render_template("complete.html")

if __name__ == "__main__":
    app.run(port=4555, debug=True) 

这是我的 .html 代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Upload here</h1>
<form id="upload-form" action="{{url_for('upload')}}" methods="POST" enctype="multipart/form-data">
    <input type="file" name="file" accept="image/*" multiple>
    <input type="submit" value="send">

</form>
</body>
</html>

标签: pythonflask

解决方案


您在定义表单的 html 标记中有错字。它应该说:

<form id="upload-form" action="{{url_for('upload')}}" method="POST" enctype="multipart/form-data">

method="POST"代替methods="POST"


推荐阅读