PAYATHON 2026

NiceGUI 上传 CSV 报错:UploadEventArguments 无 content 属性

数据小陈

结论:这个 AttributeError 多半跟文件内容无关,是 NiceGUI 版本和教程对不上。旧教程里用的是 e.content,而现在上传事件的参数通过 e.file 提供文件对象,读取字节内容要用 await e.file.read()。

原因

NiceGUI 的上传事件 API 改过几次。教程代码可能对应旧版本,那时 UploadEventArguments 带有 content 属性;你当前安装的版本没有这个属性,所以执行到 e.content.read() 就会抛出:

AttributeError: 'UploadEventArguments' object has no attribute 'content'

解决步骤

  1. 把上传处理函数改成 async def,读取 e.file 需要 await。
  2. 用 await e.file.read() 读出文件的字节内容。
  3. 对字节内容执行 decode('utf-8') 得到文本。
  4. 把文本写回 ui.markdown() 元素。

修正后的代码

from nicegui import ui, events

markdown_data = ui.markdown()

async def handle_uploads(e: events.UploadEventArguments):
    raw = await e.file.read()
    text = raw.decode('utf-8')
    markdown_data.set_content(text)

ui.upload(on_upload=handle_uploads).props('accept=.md').classes('max-w-full')

ui.run(port=8081)

后续如果要处理 CSV,可以把读到的文本交给 pandas:

import pandas as pd
from io import StringIO

async def handle_csv_upload(e: events.UploadEventArguments):
    raw = await e.file.read()
    text = raw.decode('utf-8')
    df = pd.read_csv(StringIO(text))
    markdown_data.set_content(df.to_markdown())

df.to_markdown() 需要环境里装了 tabulate;只是调试的话,先打印 df.head(),或者把 df.to_string() 写进 Markdown 也可以。

注意事项

  • 不要混用同步 def 和 await。用了 await e.file.read(),处理函数就必须是 async def。
  • 如果当前版本连 e.file 也没有,先在 handler 里打印 type(e) 和 dir(e),看你实际安装的 NiceGUI 版本提供了哪些属性。
  • props('accept=.md') 只是前端选择文件时的过滤,不能保证文件一定是 UTF-8;编码不同的话,decode('utf-8') 照样会失败。
  • 文件较大时,一次性 read() 会占用内存,这种情况要谨慎,或者考虑分片上传。

备注:内容仅供参考。