voice-changer/server/restapi/mods/FileUploader.py

33 lines
1.2 KiB
Python
Raw Normal View History

2023-02-16 21:03:21 +03:00
import os
import shutil
2022-12-31 14:25:28 +03:00
from fastapi import UploadFile
# UPLOAD_DIR = "model_upload_dir"
2023-02-16 21:03:21 +03:00
def upload_file(upload_dirname: str, file: UploadFile, filename: str):
2022-12-31 14:25:28 +03:00
if file and filename:
fileobj = file.file
2023-02-16 21:03:21 +03:00
upload_dir = open(os.path.join(upload_dirname, filename), 'wb+')
2022-12-31 14:25:28 +03:00
shutil.copyfileobj(fileobj, upload_dir)
upload_dir.close()
2023-01-10 16:49:16 +03:00
2023-02-16 21:03:21 +03:00
return {"status": "OK", "msg": f"uploaded files {filename} "}
return {"status": "ERROR", "msg": "uploaded file is not found."}
2022-12-31 14:25:28 +03:00
2023-02-16 21:03:21 +03:00
def concat_file_chunks(upload_dirname: str, filename: str, chunkNum: int, dest_dirname: str):
2022-12-31 14:25:28 +03:00
target_file_name = os.path.join(dest_dirname, filename)
2023-01-07 18:25:21 +03:00
if os.path.exists(target_file_name):
2023-02-16 21:03:21 +03:00
os.remove(target_file_name)
2022-12-31 14:25:28 +03:00
with open(target_file_name, "ab") as target_file:
for i in range(chunkNum):
chunkName = f"{filename}_{i}"
chunk_file_path = os.path.join(upload_dirname, chunkName)
stored_chunk_file = open(chunk_file_path, 'rb')
target_file.write(stored_chunk_file.read())
stored_chunk_file.close()
2023-02-16 21:03:21 +03:00
os.remove(chunk_file_path)
2022-12-31 14:25:28 +03:00
target_file.close()
2023-02-16 21:03:21 +03:00
return {"status": "OK", "msg": f"concat files {target_file_name} "}