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

使用Streamlit与OpenAI时持续遭遇UnicodeDecodeError问题求助

问题:Streamlit+OpenAI项目中UnicodeDecodeError错误排查

我尝试将OpenAI与Streamlit结合搭建一个演示网站,相关代码如下:

save_folder = "files"
if not os.path.exists(save_folder):
    os.makedirs(save_folder)

uploaded_files = st.file_uploader("Choose a file", accept_multiple_files=True)
for uploaded_file in uploaded_files:
    bytes_data = uploaded_file.read()
    s = bytes_data.decode("UTF-8")
    
    with open(f"{save_folder}/{uploaded_file.name}", "w") as f:
        f.write(s)

SimpleDirectoryReader = download_loader("SimpleDirectoryReader")
loader = SimpleDirectoryReader(save_folder)
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?")
response = index.query(question)
st.write(response)

运行时持续遇到如下错误:

File "/home/appuser/venv/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script

    exec(code, module.__dict__)

  File "/app/indextest/streamlit_app.py", line 17, in <module>

    s = bytes_data.decode("UTF-8")

UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 14-15: invalid continuation byte

错误原因

这个错误的核心是上传的文件并非UTF-8编码格式,强行用UTF-8解码非UTF-8编码的二进制数据就会触发解码失败。常见场景包括:

  • 文件使用GBK、GB2312、Latin-1等其他文本编码
  • 上传了二进制文件(如图片、PDF、压缩包),这类文件本身不是文本格式,无法用UTF-8解码

解决方法

方法一:指定对应编码解码

如果知道上传文件的具体编码(比如GBK),直接修改解码代码:

s = bytes_data.decode("GBK")

不确定编码时,可以用chardet库自动检测:

import chardet

# 检测文件编码
result = chardet.detect(bytes_data)
# 用检测出的编码解码
s = bytes_data.decode(result['encoding'])

方法二:二进制模式直接保存文件

如果不需要提前读取文件内容,只是要保存文件供后续SimpleDirectoryReader处理,直接用二进制写入可以彻底避免编码问题,同时支持所有文件类型:

with open(f"{save_folder}/{uploaded_file.name}", "wb") as f:
    f.write(bytes_data)

方法三:限制上传文件类型

在st.file_uploader中指定只接受文本文件,从源头减少非UTF-8文件的上传:

uploaded_files = st.file_uploader("Choose a text file", accept_multiple_files=True, type=["txt"])

内容的提问来源于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 22:50:46