|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +import os |
| 4 | + |
| 5 | +import aiofiles |
| 6 | + |
| 7 | +from fastapi import UploadFile |
| 8 | + |
| 9 | +from backend.common.enums import FileType |
| 10 | +from backend.common.exception import errors |
| 11 | +from backend.common.log import log |
| 12 | +from backend.core.conf import settings |
| 13 | +from backend.core.path_conf import UPLOAD_DIR |
| 14 | +from backend.utils.timezone import timezone |
| 15 | + |
| 16 | + |
| 17 | +def build_filename(file: UploadFile): |
| 18 | + """ |
| 19 | + 构建文件名 |
| 20 | +
|
| 21 | + :param file: |
| 22 | + :return: |
| 23 | + """ |
| 24 | + timestamp = int(timezone.now().timestamp()) |
| 25 | + filename = file.filename |
| 26 | + file_ext = filename.split('.')[-1].lower() |
| 27 | + new_filename = f'{filename.replace(f".{file_ext}", f"_{timestamp}")}.{file_ext}' |
| 28 | + return new_filename |
| 29 | + |
| 30 | + |
| 31 | +def file_verify(file: UploadFile, file_type: FileType) -> None: |
| 32 | + """ |
| 33 | + 文件验证 |
| 34 | +
|
| 35 | + :param file: |
| 36 | + :param file_type: |
| 37 | + :return: |
| 38 | + """ |
| 39 | + filename = file.filename |
| 40 | + file_ext = filename.split('.')[-1].lower() |
| 41 | + if not file_ext: |
| 42 | + raise errors.ForbiddenError(msg='未知的文件类型') |
| 43 | + if file_type == FileType.image: |
| 44 | + if file_ext not in settings.UPLOAD_IMAGE_EXT_INCLUDE: |
| 45 | + raise errors.ForbiddenError(msg='此图片格式暂不支持') |
| 46 | + if file.size > settings.UPLOAD_IMAGE_SIZE_MAX: |
| 47 | + raise errors.ForbiddenError(msg='图片超出最大限制,请重新选择') |
| 48 | + elif file_type == FileType.video: |
| 49 | + if file_ext not in settings.UPLOAD_VIDEO_EXT_INCLUDE: |
| 50 | + raise errors.ForbiddenError(msg='此视频格式暂不支持') |
| 51 | + if file.size > settings.UPLOAD_VIDEO_SIZE_MAX: |
| 52 | + raise errors.ForbiddenError(msg='视频超出最大限制,请重新选择') |
| 53 | + |
| 54 | + |
| 55 | +async def upload_file(file: UploadFile): |
| 56 | + """ |
| 57 | + 上传文件 |
| 58 | +
|
| 59 | + :param file: |
| 60 | + :return: |
| 61 | + """ |
| 62 | + filename = build_filename(file) |
| 63 | + try: |
| 64 | + async with aiofiles.open(os.path.join(UPLOAD_DIR, filename), mode='wb') as fb: |
| 65 | + while True: |
| 66 | + content = await file.read(settings.UPLOAD_READ_SIZE) |
| 67 | + if not content: |
| 68 | + break |
| 69 | + await fb.write(content) |
| 70 | + except Exception as e: |
| 71 | + log.error(f'上传文件 {filename} 失败:{str(e)}') |
| 72 | + raise errors.RequestError(msg='上传文件失败') |
| 73 | + finally: |
| 74 | + await file.close() |
| 75 | + return filename |
0 commit comments