@app.post("/upload")
def upload_chunk():
file = request.files["file"]
file_uuid = request.form["dzuuid"]
# Generate a unique filename to avoid overwriting using 8 chars of uuid before filename.
filename = f"{file_uuid[:8]}_{secure_filename(file.filename)}"
save_path = Path("static", "img", filename)
current_chunk = int(request.form["dzchunkindex"])
code
try:
with open(save_path, "ab") as f:
f.seek(int(request.form["dzchunkbyteoffset"]))
f.write(file.stream.read())
except OSError:
return "Error saving file.", 500
total_chunks = int(request.form["dztotalchunkcount"])
if current_chunk + 1 == total_chunks:
# This was the last chunk, the file should be complete and the size we expect
if os.path.getsize(save_path) != int(request.form["dztotalfilesize"]):
return "Size mismatch.", 500
return "Chunk upload successful.", 200
Add a queue system so only one person can upload a file and the next upload won't start until the first person presses a button
also add the ability to download the files that you uploaded
To accomplish your requirements, you will need to add a queuing mechanism and manage the file download upon completion. Here's an implementation using Python, Flask, and Redis Queue:
Install the required packages:
sh
pip install Flask Redis rq
Update app.py to include the queuing mechanism and download endpoint:
python
import os
from pathlib import Path
import uuid
from flask import Flask, render_template, request, send_from_directory, redirect, url_for
from werkzeug.utils import secure_filename
from redis import Redis
from rq import Queue
app = Flask(__name__)
queue = Queue(connection=Redis())
def process_file(file_uuid, filename):
save_path = Path("static", "img", filename)
# Add file conversion process here
# Example:
# with open(save_path, "rb") as f:
# converted_content = convert(f) # Assuming you have a 'convert' function
# with open(save_path, "wb") as f:
# f.write(converted_content)
return True
@app.get("/")
def index():
return render_template("index.html")
@app.post("/upload")
def upload_chunk():
file = request.files["file"]
file_uuid = request.form["dzuuid"]
# Generate a unique filename to avoid overwriting using 8 chars of UUID before the filename.
filename = f"{file_uuid[:8]}_{secure_filename(file.filename)}"
save_path = Path("static", "img", filename)
current_chunk = int(request.form["dzchunkindex"])
try:
with open(save_path, "ab") as f:
f.seek(int(request.form["dzchunkbyteoffset"]))
f.write(file.stream.read())
except OSError:
return "Error saving file.", 500
total_chunks = int(request.form["dztotalchunkcount"])
if current_chunk + 1 == total_chunks:
# This was the last chunk, the file should be complete and the size we expect
if os.path.getsize(save_path) != int(request.form["dztotalfilesize"]):
return "Size mismatch.", 500
# Enqueue the file for processing
result = queue.enqueue(process_file, file_uuid, filename)
return str(result.id), 200
return "Chunk upload successful.", 200
@app.route("/download/<path:filename>", methods=["GET", "POST"])
def download(filename):
static_img_path = os.path.join(app.root_path, "static", "img")
return send_from_directory(directory=static_img_path, filename=filename, as_attachment=True)
@app.route("/downloads/<string:queue_id>", methods=["GET"])
def check_queue(queue_id):
job = queue.fetch_job(queue_id)
if job is None:
return "Job not found", 404
elif job.is_failed:
return "Job failed", 500
elif job.result:
return redirect(url_for("download", filename=job.result))
else:
return "Still processing...", 202
if __name__ == "__main__":
app.run(debug=True)
Modify index.html to handle the new queue ID received and poll the server to check if the conversion is complete and ready for download:
Now, your app will allow users to upload files one by one, process them, and download the processed files. Note that this example takes a simplistic approach to queuing and processing, and you might need to enhance and optimize it further depending on your use case. Also, consider using a more advanced task queue like Celery for more complex processing pipelines.