这个问题可能是由于发送的文件名包含了中文字符或其他特殊字符所导致的。解决这个问题的方法是在发送文件时,使用urlencode()函数将文件名编码为URL可接受的格式,并在请求头中设置Content-Disposition,指定文件名。
以下是使用aiohttp session.post()发送文件的示例代码:
import aiohttp
import urllib.parse
async def send_file():
url = 'http://example.com/upload'
file_path = '/path/to/file'
file_name = '文件名 with 中文.txt'
async with aiohttp.ClientSession() as session:
data = aiohttp.FormData()
data.add_field('file', open(file_path, 'rb'), filename=urllib.parse.quote(file_name))
headers = {
'Content-Disposition': f'attachment; filename="{file_name}"'
}
async with session.post(url, data=data, headers=headers) as resp:
response_text = await resp.text()
print(response_text)
在这个示例代码中,我们使用了urlencode()函数将文件名编码为URL可接受的格式,并将编码后的文件名作为filename参数传递给data.add_field()函数。另外,我们也在请求头中设置了Content-Disposition,指定了文件名。这样,文件就能够成功上传了。