bugfix
This commit is contained in:
parent
97ef9067d3
commit
54b41c7160
24
woa/media.py
24
woa/media.py
@ -91,35 +91,41 @@ class WeChatMediaManager:
|
|||||||
else:
|
else:
|
||||||
url = f"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={token}&type={media_type}"
|
url = f"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={token}&type={media_type}"
|
||||||
|
|
||||||
# 构建 multipart/form-data
|
|
||||||
form = aiohttp.FormData()
|
form = aiohttp.FormData()
|
||||||
with open(file_path, 'rb') as f:
|
f = open(file_path, 'rb') # 不用 with
|
||||||
# 微信要求的字段名必须是 'media'
|
try:
|
||||||
form.add_field('media', f, filename=os.path.basename(file_path))
|
form.add_field(
|
||||||
|
'media',
|
||||||
|
f,
|
||||||
|
filename=os.path.basename(file_path),
|
||||||
|
content_type='application/octet-stream'
|
||||||
|
)
|
||||||
|
|
||||||
# 永久视频需要额外的 description 字段 (JSON 格式)
|
|
||||||
if is_permanent and media_type == 'video':
|
if is_permanent and media_type == 'video':
|
||||||
if not title:
|
if not title:
|
||||||
title = os.path.basename(file_path)
|
title = os.path.basename(file_path)
|
||||||
|
|
||||||
desc_json = json.dumps({
|
desc_json = json.dumps({
|
||||||
"title": title,
|
"title": title,
|
||||||
"introduction": description or ""
|
"introduction": description or ""
|
||||||
}, ensure_ascii=False)
|
}, ensure_ascii=False)
|
||||||
|
|
||||||
form.add_field('description', desc_json)
|
form.add_field('description', desc_json)
|
||||||
|
|
||||||
timeout = aiohttp.ClientTimeout(total=120) # 大文件上传需要更长超时
|
timeout = aiohttp.ClientTimeout(total=120)
|
||||||
|
|
||||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||||
async with session.post(url, data=form) as resp:
|
async with session.post(url, data=form) as resp:
|
||||||
result = await resp.json()
|
result = await resp.json()
|
||||||
|
|
||||||
if resp.status == 200 and ('media_id' in result or 'url' in result):
|
if resp.status == 200 and ('media_id' in result or 'url' in result):
|
||||||
debug(f"上传成功 ({'永久' if is_permanent else '临时'}): {result.get('media_id')}")
|
return result['media_id']
|
||||||
return result
|
|
||||||
else:
|
else:
|
||||||
error(f"上传失败: {result}")
|
|
||||||
raise Exception(f"WeChat Upload Error: {result}")
|
raise Exception(f"WeChat Upload Error: {result}")
|
||||||
|
|
||||||
|
finally:
|
||||||
|
f.close() # 手动关闭
|
||||||
|
|
||||||
# ================= 3. 下载媒体文件 =================
|
# ================= 3. 下载媒体文件 =================
|
||||||
async def download_media(
|
async def download_media(
|
||||||
self,
|
self,
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user