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

ipyvuetify FileInput组件无法通过v_model获取选中文件该如何处理?

ipyvuetify FileInput 获取选中文件的解决方案

默认配置下,ipyvuetify的FileInput不会主动将选中文件的信息同步到Python内核,所以直接读取v_model或者change事件的回调参数都会得到空值。

完整可运行代码

import ipyvuetify as v
from ipywidgets import Output

# 用于输出文件信息
output = Output()

def file_selected(widget, event, data):
    with output:
        output.clear_output()
        # 选中的文件全部存在widget.files列表中
        for file in widget.files:
            print(f"文件名:{file['name']}")
            print(f"文件大小:{file['size']} 字节")
            print(f"文件类型:{file['type']}")
            # 读取文件内容,返回字节格式
            content = file['file_obj'].read()
            # 文本文件可以直接解码
            # text_content = content.decode('utf-8')
            print(f"文件前100字节:{content[:100]}")

# 初始化FileInput,必须开启show_size触发文件同步
filefield = v.FileInput(
    v_model='',
    placeholder='选择文件...',
    multiple=False, # 如需多选改为True
    show_size=True, # 核心配置,开启后文件信息会同步到Python侧
    clearable=True
)
# 绑定change事件
filefield.on_event('change', file_selected)

# 显示组件和输出框
display(filefield, output)

关键说明

  • show_size=True是触发文件信息同步的核心配置,哪怕不需要展示文件大小也需要保留该配置,否则组件不会将文件数据传到Python后端。
  • 所有选中的文件都存储在组件的files列表属性中,每个元素是包含文件名、大小、类型、文件对象的字典,通过file_obj.read()即可读取完整文件内容。
  • 多选场景只需将multiple设置为True,遍历files列表即可读取所有选中的文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:30:01