I've got a simple flask app that takes form input from the user in addition to file uploads. I can get the files uploaded to a directory on the disk just fine, but the problem I'm running into is that when multiple users try to upload files, all the files get thrown into the same folder and there is no telling who uploaded what.
To solve this, I've been trying to dynamically create a directory name at the end of the file path for each user. Ideally this directory name will pull from the form data (EX: Business Name) and the associated files will get uploaded in a neat, organized fashion. I've tried pathlib and os.path.exists and neither seems to be working. I keep getting a directory created called 'None' and I can't figure it out for the life of me. Any help would be much appreciated.
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")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…