Last active
October 10, 2023 06:59
-
-
Save CheeseCake87/f99485a5e7f3055379b831e5ae2bcbd6 to your computer and use it in GitHub Desktop.
Flask file upload with pathlib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pathlib | |
import random | |
from textwrap import dedent | |
from flask import Flask, request, abort | |
from werkzeug.utils import secure_filename | |
def create_app(): | |
app = Flask(__name__, static_url_path="/") | |
upload_folder = pathlib.Path(pathlib.Path(app.root_path) / "uploads") | |
app.static_folder = upload_folder | |
if not upload_folder.exists(): | |
upload_folder.mkdir() | |
@app.route("/", methods=["GET", "POST"]) | |
def index(): | |
if request.method == "GET": | |
return """ | |
<html> | |
<body> | |
<form method="POST" enctype="multipart/form-data"> | |
<input type="file" name="images" /> | |
<label> | |
Randomize File Name | |
<input type="checkbox" name="randomise_name" /> | |
</label> | |
<input type="submit" value="Submit" /> | |
</form> | |
</body> | |
</html> | |
""" | |
if request.method == "POST": | |
filepaths = [] | |
images = request.files.getlist("images") | |
for image in images: | |
file_staging = upload_folder / secure_filename(image.filename) | |
print(dedent( | |
f""" | |
=================== | |
file_staging: {file_staging} | |
file_staging.parent: {file_staging.parent} | |
file_staging.parts: {file_staging.parts} | |
file_staging.name: {file_staging.name} | |
file_staging.stem: {file_staging.stem} | |
file_staging.suffix: {file_staging.suffix} | |
file_staging.anchor: {file_staging.anchor} | |
file_staging.exists(): {file_staging.exists()} | |
=================== | |
""" | |
)) | |
if "randomise_name" in request.form: | |
random_filename = upload_folder / f"{random.randrange(1111, 9999)}{file_staging.suffix}" | |
filepaths.append(f'<img style="width: 250px" src="/{random_filename.name}" />') | |
image.save(random_filename) | |
else: | |
filepaths.append(f'<img style="width: 250px" src="/{file_staging.name}" />') | |
image.save(file_staging) | |
return f""" | |
<html> | |
<body> | |
<p>Images uploaded successfully.</p> | |
<a href="/">Upload more images</a> | |
<br/> | |
{'<br/>'.join(filepaths)} | |
</body> | |
</html> | |
""" | |
return app | |
if __name__ == '__main__': | |
create_app().run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment