Skip to content

Commit bcf0be3

Browse files
committed
调整文件大小计算和写入方法
1 parent d4209bb commit bcf0be3

File tree

2 files changed

+35
-19
lines changed

2 files changed

+35
-19
lines changed

main.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import asyncio
55
from pathlib import Path
66

7-
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException
7+
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException, BackgroundTasks
88
from starlette.responses import HTMLResponse, FileResponse
99
from starlette.staticfiles import StaticFiles
1010

@@ -130,8 +130,8 @@ async def index(code: str, ip: str = Depends(ip_limit), s: AsyncSession = Depend
130130

131131

132132
@app.post('/share')
133-
async def share(text: str = Form(default=None), style: str = Form(default='2'), value: int = Form(default=1),
134-
file: UploadFile = File(default=None), s: AsyncSession = Depends(get_session)):
133+
async def share(background_tasks: BackgroundTasks, text: str = Form(default=None), style: str = Form(default='2'),
134+
value: int = Form(default=1), file: UploadFile = File(default=None), s: AsyncSession = Depends(get_session)):
135135
code = await get_code(s)
136136
if style == '2':
137137
if value > 7:
@@ -148,11 +148,11 @@ async def share(text: str = Form(default=None), style: str = Form(default='2'),
148148
exp_count = -1
149149
key = uuid.uuid4().hex
150150
if file:
151-
file_bytes = await file.read()
152-
size = len(file_bytes)
151+
size = await storage.get_size(file)
153152
if size > settings.FILE_SIZE_LIMIT:
154153
raise HTTPException(status_code=400, detail="文件过大")
155-
_text, _type, name = await storage.save_file(file, file_bytes, key), file.content_type, file.filename
154+
_text, _type, name = await storage.get_text(file, key), file.content_type, file.filename
155+
background_tasks.add_task(storage.save_file, file, _text)
156156
else:
157157
size, _text, _type, name = len(text), text, 'text', '文本分享'
158158
info = Codes(

storage.py

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import os
22
import asyncio
3-
import datetime
3+
from datetime import datetime
44
from pathlib import Path
5+
from typing import BinaryIO
6+
7+
from fastapi import UploadFile
58

69
import settings
710

@@ -11,25 +14,38 @@ class FileSystemStorage:
1114
STATIC_URL = settings.STATIC_URL
1215
NAME = "filesystem"
1316

14-
async def get_filepath(self, path):
15-
return self.DATA_ROOT / path.lstrip(self.STATIC_URL + '/')
16-
17-
def _save(self, filepath, file_bytes):
18-
with open(filepath, 'wb') as f:
19-
f.write(file_bytes)
17+
async def get_filepath(self, text: str):
18+
return self.DATA_ROOT / text.lstrip(self.STATIC_URL + '/')
2019

21-
async def save_file(self, file, file_bytes, key):
22-
now = datetime.datetime.now()
23-
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
20+
async def get_text(self, file: UploadFile, key: str):
2421
ext = file.filename.split('.')[-1]
25-
name = f'{key}.{ext}'
22+
now = datetime.now()
23+
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
2624
if not path.exists():
2725
path.mkdir(parents=True)
28-
filepath = path / name
29-
await asyncio.to_thread(self._save, filepath, file_bytes)
26+
filepath = path / f'{key}.{ext}'
3027
text = f"{self.STATIC_URL}/{filepath.relative_to(self.DATA_ROOT)}"
3128
return text
3229

30+
async def get_size(self, file: UploadFile):
31+
f = file.file
32+
f.seek(0, os.SEEK_END)
33+
size = f.tell()
34+
f.seek(0, os.SEEK_SET)
35+
return size
36+
37+
def _save(self, filepath, file: BinaryIO):
38+
with open(filepath, 'wb') as f:
39+
chunk_size = 256 * 1024
40+
chunk = file.read(chunk_size)
41+
while chunk:
42+
f.write(chunk)
43+
chunk = file.read(chunk_size)
44+
45+
async def save_file(self, file: UploadFile, text: str):
46+
filepath = await self.get_filepath(text)
47+
await asyncio.to_thread(self._save, filepath, file.file)
48+
3349
async def delete_file(self, file):
3450
# 是文件就删除
3551
if file['type'] != 'text':

0 commit comments

Comments
 (0)