feat: optimzie file model
This commit is contained in:
+13
-4
@@ -2,6 +2,7 @@ import datetime
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
import aiofiles
|
||||||
from fastapi import UploadFile
|
from fastapi import UploadFile
|
||||||
from sqlmodel import Field
|
from sqlmodel import Field
|
||||||
|
|
||||||
@@ -45,9 +46,13 @@ class FileSaveService:
|
|||||||
datetime_string = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
datetime_string = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
||||||
file_id = f"{datetime_string}_{id}"
|
file_id = f"{datetime_string}_{id}"
|
||||||
|
|
||||||
|
# 文件的保存路径,用来将文件写入到磁盘
|
||||||
|
# save_path=/www/wwwroot/web/web/upload_file/时间+随机ID
|
||||||
save_path = path_join(env.file_save_path, file_id).replace('\\', '/')
|
save_path = path_join(env.file_save_path, file_id).replace('\\', '/')
|
||||||
print("save_path", save_path)
|
print("save_path", save_path)
|
||||||
|
|
||||||
|
# 文件的访问路径,用来生成文件的访问路径,然后存到附件表中的path字段中
|
||||||
|
# public_path=/web/upload_file/时间+随机ID
|
||||||
public_path = path_join(env.file_public_path, file_id).replace('\\', '/')
|
public_path = path_join(env.file_public_path, file_id).replace('\\', '/')
|
||||||
print("public_path", public_path)
|
print("public_path", public_path)
|
||||||
|
|
||||||
@@ -55,11 +60,15 @@ class FileSaveService:
|
|||||||
# exist_ok=True 表示如果目录已存在不抛出异常
|
# exist_ok=True 表示如果目录已存在不抛出异常
|
||||||
Path(save_path).mkdir(parents=True, exist_ok=True)
|
Path(save_path).mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
file_save_path = path_join(save_path, filename)
|
file_save_path = path_join(save_path, filename) # 文件的保存路径
|
||||||
file_public_path = path_join(public_path, filename)
|
file_public_path = path_join(public_path, filename) # 文件的访问路径
|
||||||
|
|
||||||
with open(file_save_path, 'wb') as f:
|
# with open(file_save_path, 'wb') as f:
|
||||||
f.write(await file.read())
|
# f.write(await file.read())
|
||||||
|
|
||||||
|
async with aiofiles.open(file_save_path, 'wb') as f:
|
||||||
|
await f.write(await file.read())
|
||||||
|
await f.flush() # 确保数据写入磁盘
|
||||||
|
|
||||||
file_dict = {
|
file_dict = {
|
||||||
"id": id,
|
"id": id,
|
||||||
|
|||||||
Reference in New Issue
Block a user