我有一个用例将从客户端(前端/邮递员)接收到的文件和其他表单数据发送到文件上传服务以上传文件。为此,我使用
aiohttp
。在请求正文中发送时我遇到了几个问题。
# View
from fastapi import APIRouter, Request
from app.services.file_upload_service import FileUploadClient
file_upload_router = APIRouter(prefix="/file_upload")
@file_upload_router.post("/")
async def upload_files(request: Request):
req = await request.form()
file = req._dict.get("file") # type --> <class 'tempfile.SpooledTemporaryFile'>
response = await FileUploadClient.upload_file(file)
return Response(...)
# util
class FileUploadClient(someClass):
...
...
@classmethod
async def upload_file(cls, file):
if not file:
return None
url = "endpoint_to_file_upload_service"
file_name = file.filename
data_dict = {'file_name': file_name, 'form_data_key1': 'val1', 'form_data_key2': 'val2'}
formdata = aiohttp.FormData()
for key, value in data_dict.items():
formdata.add_field(key, value)
formdata.add_field('file', file.file)
print(type(file.file))
auth = await cls.get_auth() # This is BasicAuth: aiohttp.BasicAuth(username, password)
async with aiohttp.ClientSession() as session:
async with session.request("post", url, data=formdata, auth=auth, timeout=5) as response:
resp = await response.json()
print(resp)
return resp
这会引发错误:
{'detail': 'Unsupported media type "application/x-www-form-urlencoded" in request.'}
当保持标题为 NULL 时,
当在标题中发送
application/json
作为content-type
时,它正在抛出{'detail': 'Unsupported media type "application/json" in request.'}
当我发送从客户端接收到的相同标头时,上述问题就消失了,但在文件上传服务中接收到的正文为空正文。
我该如何解决这个问题?