You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FSM-aiogram 文件获取问题:如何下载用户触发发送的文件?

解决aiogram中FSM模式下的文件下载问题

你的代码已经正确获取了文件的file_id和远程路径file_path,但缺少实际下载文件到本地的步骤。只需添加bot.download_file()方法即可完成下载,同时建议增加消息类型过滤避免报错,具体修改如下:

修改后的完整代码

@dp.message_handler(text_contains='Send file')
async def start_bots(msg):
    await bot.send_message(msg.from_user.id, 'Ok, send me a file')
    await HZ.getFile.set()

# 添加content_types过滤器,只处理文档类型消息
@dp.message_handler(content_types=['document'], state=HZ.getFile)
async def getID(msg: types.Message, state: FSMContext):
    file_id = msg.document.file_id
    file = await bot.get_file(file_id)
    file_path = file.file_path
    
    # 核心:调用download_file下载文件到本地,指定保存路径和文件名
    # 这里使用用户上传的原文件名,也可以自定义命名
    await bot.download_file(file_path, destination=f"./{msg.document.file_name}")
    
    print(f"文件已下载到本地:./{msg.document.file_name}")
    await state.finish()

关键说明

  • 添加消息类型过滤:在第二个消息处理器中加入content_types=['document'],确保只有用户发送文档时才触发该函数,避免用户发送其他类型消息(如文本、图片)导致msg.document报错。
  • 执行下载操作:await bot.download_file(file_path, destination=保存路径)是核心方法,destination参数指定文件保存到本地的路径和文件名,示例中直接复用用户上传的原文件名,也可根据需求自定义。

内容的提问来源于stack exchange,提问作者kamazz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 02:50:54