在 Flask 中动态创建文件上传路径会导致创建“无”目录

问题描述

我有一个简单的烧瓶应用程序,除了文件上传之外,它还从用户那里获取表单输入。我可以将文件上传到磁盘上的目录就好了,但是我遇到的问题是当多个用户尝试上传文件时,所有文件都被扔到同一个文件夹中,并且不知道是谁上传了什么.

为了解决这个问题,我一直在尝试在每个用户文件路径末尾动态创建一个目录名。理想情况下,此目录名称将从表单数据(例如:企业名称)中提取,并且相关文件将以整洁、有组织的方式上传。我试过 pathlib 和 os.path.exists ,但似乎都没有工作。我一直在创建一个名为“无”的目录,但我一生都无法弄清楚。任何帮助将不胜感激。

app.py

@app.route('/',methods=["POST","GET"])
 def upload():
  if request.method == "POST":

    # Retreive form inputs
    req = request.form

    fName = req.get("inputFName")
    lName = req.get("inputLName")
    email = req.get("inputEmail")
    phone = req.get("inputPhone")
    business = req.get("inputBusiness")
    TIN = req.get("inputTIN")

    parent_path = app.config["FILE_UPLOADS"]
    uploads = request.files.items()
    business_string = str(business)
    business_secure = secure_filename(business_string)

    pathlib.Path(parent_path,business_secure).mkdir(exist_ok=True)

    # Loop through each file and upload
    for key,f in uploads:
        if key.startswith('file'):

            # Get filename
            filename = secure_filename(f.filename)

            # If user does not select file
            # submit an empty part message without filename
            if filename == "":
                flash("No file detected. Please upload requested files and try agin.","danger")
                return redirect(request.url)

            if f and allowed_file(filename):
                f.save(os.path.join(parent_path,business_secure,filename))
                print("Success! File: " + filename)

            else:
                print("FAIL!")

        else:
            print("No file part")
            return redirect(request.url)

    # Upload success message
    flash("Application upload successful! A member of our team will reach out to you regarding next steps","success")
    return redirect(request.url)

return render_template("public/index.html")

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)