From 54b41c71601fd123e4181f85526a00ae7cfcad67 Mon Sep 17 00:00:00 2001 From: yumoqing Date: Tue, 3 Mar 2026 16:31:38 +0800 Subject: [PATCH] bugfix --- woa/media.py | 54 +++++++++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/woa/media.py b/woa/media.py index c30c657..3953ab5 100644 --- a/woa/media.py +++ b/woa/media.py @@ -91,34 +91,40 @@ class WeChatMediaManager: else: url = f"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={token}&type={media_type}" - # 构建 multipart/form-data - form = aiohttp.FormData() - with open(file_path, 'rb') as f: - # 微信要求的字段名必须是 'media' - form.add_field('media', f, filename=os.path.basename(file_path)) + form = aiohttp.FormData() + f = open(file_path, 'rb') # 不用 with + try: + 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 not title: - title = os.path.basename(file_path) - desc_json = json.dumps({ - "title": title, - "introduction": description or "" - }, ensure_ascii=False) - form.add_field('description', desc_json) + if is_permanent and media_type == 'video': + if not title: + title = os.path.basename(file_path) - timeout = aiohttp.ClientTimeout(total=120) # 大文件上传需要更长超时 + desc_json = json.dumps({ + "title": title, + "introduction": description or "" + }, ensure_ascii=False) - async with aiohttp.ClientSession(timeout=timeout) as session: - async with session.post(url, data=form) as resp: - result = await resp.json() + form.add_field('description', desc_json) - 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 - else: - error(f"上传失败: {result}") - raise Exception(f"WeChat Upload Error: {result}") + timeout = aiohttp.ClientTimeout(total=120) + + async with aiohttp.ClientSession(timeout=timeout) as session: + async with session.post(url, data=form) as resp: + result = await resp.json() + + if resp.status == 200 and ('media_id' in result or 'url' in result): + return result['media_id'] + else: + raise Exception(f"WeChat Upload Error: {result}") + + finally: + f.close() # 手动关闭 # ================= 3. 下载媒体文件 ================= async def download_media(