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

使用Streamlit开发项目时遭遇OSError: [Errno 36]文件名过长错误求助

问题排查与解决

错误原因

你误用了SimpleDirectoryReader:它的参数需要是目录路径字符串,但你把上传文件的完整内容字符串传进去了。系统把超长的文件内容当成了目录名,触发了OSError: [Errno 36] File name too long错误。

看错误栈的关键触发点:

File "/app/indextest/streamlit_app.py", line 17, in
loader = SimpleDirectoryReader(s)

这里的s是上传文件解码后的完整内容,不是合法的目录路径,导致后续input_dir.iterdir()尝试遍历一个不存在的、超长"目录",直接报错。

修复方案

根据需求,有两种正确的处理方式:

方式1:直接用文件内容创建文档(推荐)

不需要依赖SimpleDirectoryReader,直接把上传文件的内容转换成Document对象即可:

from llama_index import Document, GPTSimpleVectorIndex

uploaded_files = st.file_uploader("Choose a file", accept_multiple_files=True)
for uploaded_file in uploaded_files:
    bytes_data = uploaded_file.read()
    # 将文件内容转为Document对象
    doc = Document(text=bytes_data.decode("UTF-8"))
    # 创建索引
    index = GPTSimpleVectorIndex([doc])
    index.save_to_disk('index.json')
    
    question = st.text_input("What do you want me to do with the file uploaded?")
    if question:
        response = index.query(question)
        st.write(response)

方式2:临时保存文件到目录,再用SimpleDirectoryReader读取

如果必须使用SimpleDirectoryReader,可以把上传的文件临时保存到一个目录,再传入目录路径:

import os
from llama_index import SimpleDirectoryReader, GPTSimpleVectorIndex
import tempfile

uploaded_files = st.file_uploader("Choose a file", accept_multiple_files=True)
# 创建临时目录
with tempfile.TemporaryDirectory() as temp_dir:
    for uploaded_file in uploaded_files:
        # 保存上传的文件到临时目录
        file_path = os.path.join(temp_dir, uploaded_file.name)
        with open(file_path, "wb") as f:
            f.write(uploaded_file.getbuffer())
        
        # 用目录路径初始化SimpleDirectoryReader
        loader = SimpleDirectoryReader(temp_dir)
        documents = loader.load_data()
        index = GPTSimpleVectorIndex(documents)
        index.save_to_disk('index.json')
        
        question = st.text_input("What do you want me to do with the file uploaded?")
        if question:
            response = index.query(question)
            st.write(response)

额外优化建议

  • 把download_loader("SimpleDirectoryReader")移到循环外面,避免重复下载加载器
  • 添加文件编码异常处理(比如文件非UTF-8编码时的报错捕获)
  • 多文件上传时,可根据需求选择合并索引或分别处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:20:53