45 lines
1.2 KiB
Python
45 lines
1.2 KiB
Python
from typing import Annotated
|
||
|
||
from fastapi import APIRouter, File, Form, Request, UploadFile
|
||
|
||
from src.templates import templates
|
||
|
||
router = APIRouter()
|
||
|
||
|
||
@router.get('/')
|
||
def get_view(request: Request):
|
||
return templates.TemplateResponse(
|
||
'sample_send_file.html',
|
||
{
|
||
'request': request
|
||
}
|
||
)
|
||
|
||
|
||
@router.post('/')
|
||
# file.readがCoroutineが返ってくるため、必ずasync関数にする
|
||
async def post_view(
|
||
# formからファイルを受け取る。(formタグにenctype="multipart/form-data"を指定すること)
|
||
file: Annotated[UploadFile, File()],
|
||
message: str = Form()
|
||
):
|
||
# ファイルを読み込む(Coroutineが取れるため、必ずawaitする)
|
||
file_bytes = await file.read()
|
||
# 閉じとく
|
||
await file.close()
|
||
# 読み込んだファイルはbytesで返ってくるので、デコードする
|
||
file_content = file_bytes.decode()
|
||
print(file_content)
|
||
try:
|
||
return {
|
||
# ファイル名
|
||
"file_name": file.filename,
|
||
# ファイルのバイト数
|
||
"file_size": file.size,
|
||
# Content-Type
|
||
"file_content_type": file.content_type
|
||
}
|
||
except Exception:
|
||
return {'code': 'fail'}
|