初始化预签名上传,S3返回直传URL,其他存储返回代理URL
(
data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"])
)
| 664 | |
| 665 | @presign_api.post("/upload/init", dependencies=[Depends(share_required_login)]) |
| 666 | async def presign_upload_init( |
| 667 | data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"]) |
| 668 | ): |
| 669 | """初始化预签名上传,S3返回直传URL,其他存储返回代理URL""" |
| 670 | validate_file_type(data.file_name) |
| 671 | if data.file_size > settings.uploadSize: |
| 672 | raise HTTPException( |
| 673 | 403, |
| 674 | f"文件大小超过限制,最大为 {settings.uploadSize / (1024 * 1024):.2f} MB", |
| 675 | ) |
| 676 | if data.expire_style not in settings.expireStyle: |
| 677 | raise HTTPException(400, "过期时间类型错误") |
| 678 | |
| 679 | upload_id = uuid.uuid4().hex |
| 680 | path, _, _, filename, save_path = await FileUploadService.generate_file_path( |
| 681 | data.file_name, upload_id |
| 682 | ) |
| 683 | |
| 684 | storage: FileStorageInterface = storages[settings.file_storage]() |
| 685 | presigned_url = await storage.generate_presigned_upload_url( |
| 686 | save_path, PRESIGN_SESSION_EXPIRES |
| 687 | ) |
| 688 | |
| 689 | mode = "direct" if presigned_url else "proxy" |
| 690 | proxy_urls = build_proxy_upload_urls(upload_id) |
| 691 | upload_url = presigned_url or proxy_urls["proxy_upload_url"] |
| 692 | |
| 693 | await PresignUploadSession.create( |
| 694 | upload_id=upload_id, |
| 695 | file_name=filename, |
| 696 | file_size=data.file_size, |
| 697 | save_path=save_path, |
| 698 | mode=mode, |
| 699 | expire_value=data.expire_value, |
| 700 | expire_style=data.expire_style, |
| 701 | expires_at=await get_now() + timedelta(seconds=PRESIGN_SESSION_EXPIRES), |
| 702 | ) |
| 703 | |
| 704 | ip_limit["upload"].add_ip(ip) |
| 705 | detail = { |
| 706 | "upload_id": upload_id, |
| 707 | "upload_url": upload_url, |
| 708 | "mode": mode, |
| 709 | "expires_in": PRESIGN_SESSION_EXPIRES, |
| 710 | } |
| 711 | if mode == "proxy": |
| 712 | detail.update(proxy_urls) |
| 713 | |
| 714 | return APIResponse( |
| 715 | detail=detail |
| 716 | ) |
| 717 | |
| 718 | |
| 719 | @presign_api.put( |
nothing calls this directly
no test coverage detected