python - 在 Flask 中动态创建文件上传路径会导致创建“无”目录
问题描述
我有一个简单的烧瓶应用程序,除了文件上传之外,它还接受用户的表单输入。我可以将文件上传到磁盘上的目录就好了,但我遇到的问题是当多个用户尝试上传文件时,所有文件都被扔到同一个文件夹中,不知道是谁上传了什么.
为了解决这个问题,我一直在尝试在每个用户的文件路径末尾动态创建一个目录名。理想情况下,此目录名称将从表单数据中提取(例如:企业名称),并且相关文件将以整洁、有组织的方式上传。我已经尝试过 pathlib 和 os.path.exists ,但似乎都没有工作。我不断创建一个名为“无”的目录,但我一生都无法弄清楚。任何帮助将非常感激。
应用程序.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")
解决方案
推荐阅读
- python - "\n" 函数如何处理变量?
- c++ - setlayout上的Qt分段错误
- javascript - 将tailwindcss应用于我的反应应用程序后,我在执行“纱线启动”时遇到问题
- jquery - CSS 裁剪图像展开 OnClick?
- objective-c - NSDatePicker 专注于月份编辑
- winforms - Syncfusion Metro 表格:标题栏下方的白线
- google-apps-script - 自动将数据(当前时间)输入谷歌表单
- python-2.7 - 如何在 Tkinter 中插入脚本?
- macos - 从 NSStatusItem 显示主窗口的问题
- json - 如何将 DynamoTableItems 类型输出到 IEnumeral 列表