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

Streamlit跨浏览器文件夹命名不一致问题求解决方案

问题分析与解决方案

问题根源

Chrome内核浏览器出于安全限制,在文件上传时只会返回纯文件名(如file.txt),不会包含任何本地路径信息;而Firefox在部分场景下(比如直接从文件夹批量选择文件)会返回带父文件夹名的文件名格式(如folder/file.txt),这就导致你的代码在Firefox能正常提取文件夹名,但在Chrome中Path(uploaded_file.name).parent.name得到的是空字符串,所以页面无内容显示。

可行解决方案

方案1:开启文件夹上传(推荐)

利用Streamlit的allow_folder_upload=True参数,让用户上传整个文件夹。此时无论Chrome还是Firefox,上传后的文件对象都会包含相对路径信息,能正确提取文件夹名。

修改后的代码:

import streamlit as st
from pathlib import Path

uploaded_files = st.sidebar.file_uploader(
    "选择文件夹或文件", 
    type="txt", 
    accept_multiple_files=True,
    allow_folder_upload=True  # 启用文件夹上传功能
)
if uploaded_files:
    for uploaded_file in uploaded_files:
        folder_name = Path(uploaded_file.name).parent.name
        st.write(f"原始文件所在文件夹: {folder_name}")

方案2:手动输入文件夹名(备选)

如果必须上传单个文件,由于Chrome的安全限制无法自动获取本地文件夹名,只能让用户手动输入文件夹名称:

import streamlit as st

uploaded_files = st.sidebar.file_uploader("选择文件", type="txt", accept_multiple_files=True)
folder_name = st.sidebar.text_input("输入文件所在文件夹名称")

if uploaded_files and folder_name:
    for uploaded_file in uploaded_files:
        st.write(f"原始文件所在文件夹: {folder_name}")

注意事项

  • 浏览器的路径隐藏是安全规范,无法通过前端或后端代码绕过,所以方案1是最可靠的跨浏览器解决方案。
  • 确保你的Streamlit版本≥1.18.0(你当前使用的1.39.0满足要求),allow_folder_upload参数才可用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:18:22