feat: ファイルアップロードのサンプル

This commit is contained in:
shimoda.m@nds-tyo.co.jp 2023-06-01 15:03:08 +09:00
parent 62478a2b93
commit 1626c38d22
3 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,44 @@
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'}

View File

@ -7,6 +7,7 @@ from starlette import status
import src.static as static
from src.controller import (bio, bio_download, healthcheck, login, logout,
menu, root)
from src.controller.sample_send_file import router as sample_router
from src.core import tasks
from src.error.exception_handler import http_exception_handler
from src.error.exceptions import UnexpectedException
@ -31,6 +32,9 @@ app.include_router(bio_download.router, prefix='/bio')
# ヘルスチェック用のルーター
app.include_router(healthcheck.router, prefix='/healthcheck')
# サンプル実装、ファイル送信ルーター
app.include_router(sample_router, prefix='/sample')
# エラー発生時にログアウト画面に遷移させるハンドラー
app.add_exception_handler(status.HTTP_401_UNAUTHORIZED, http_exception_handler)
app.add_exception_handler(status.HTTP_403_FORBIDDEN, http_exception_handler)

View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="ja">
<head>
{% with subtitle = 'サンプルファイル送信' %}
{% include '_header.html' %}
{% endwith %}
<link href="/static/css/menuStyle.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid text-center background">
<h1>サンプルファイル送信</h1>
<br><br>
<form name="login" class="text-center" method="post" action="/sample/" enctype="multipart/form-data">
<div class="form-group">
<label for="file">Choose File.</label>
<input type="file" name="file" class="form-control-file" required>
</div>
<div class="form-group">
<label for="message">メッセージ</label>
<input type="text" name="message" class="form-control">
</div>
<input type="submit" id="login_button" name="login" class="btn btn-info btn-lg btn_width" id="submit" value="送信">
</form>
</div>
</body>
</html>