aiohttp文件上传的几种方式
Janz Lv4
本文距离上次更新已过去 0 天,部分内容可能已经过时,请注意甄别。

从本地文件上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import asyncio
from aiohttp import ClientSession
from aiohttp.formdata import FormData

async def upload(file_path, file_name):
async with ClientSession() as session:
data = FormData()
data.add_field(
'file',
Path(res_path).open(mode="rb"),
filename=file_name
)
url = f''
async with session.post( url, data=data) as resp:
assert resp.status == 200

asyncio.run(upload(f'./test.jpeg', 'test.jpg'))

从文件流上传

这种方式不需要把文件保存到本地,采用流的方式进行传输。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import asyncio
from aiohttp import ClientSession
from aiohttp.formdata import FormData

async def upload_stream(res_url, url, file_name):
async with ClientSession() as session:
async with session.get(res_url) as r:
data = FormData()
data.add_field('file', r.content, filename=filename)
async with session.post(url, data=data) as resp:
assert resp.status == 200

asyncio.run(upload_stream(f'<res_url>', f'<upload_url>', 'test.jpg'))

Enjoy!

Client Quickstart — aiohttp 3.8.4 documentation

 评论
评论插件加载失败
正在加载评论插件
由 Hexo 驱动 & 主题 Keep