Many issues where others’ effective methods cannot be displayed on our own interface are often related to the browser and streamlit version. Therefore, the first step is to check your browser. Use the inspection function to find in the page source code:
<span class="st-emotion-cache-9ycgxx e16xj5sw3">Drag and drop file here</span>
<small class="st-emotion-cache-1rpn56r ejh2rmr0">Limit 200MB per file</small>
find content in your class
Then you can rewrite the following code according to your output::
import streamlit as st
st.set_page_config(page_title="文件上传器样式测试", layout="wide")
# 自定义CSS样式
custom_css = """
<style>
/* 隐藏所有默认文本 */
[data-testid="stFileUploader"] .st-emotion-cache-9ycgxx,
[data-testid="stFileUploader"] .css-9ycgxx,
[data-testid="stFileUploader"] .st-emotion-cache-1rpn56r,
[data-testid="stFileUploader"] .css-1rpn56r {
display: none !important;
}
/* 为文件上传器添加自定义样式和文本 */
[data-testid="stFileUploader"] {
position: relative !important;
min-height: 70px !important; /* 进一步缩小高度 */
max-width: 350px !important; /* 限制最大宽度 */
margin: 0 auto !important; /* 居中显示 */
border: 2px dashed #ddd !important; /* 添加虚线边框 */
border-radius: 8px !important; /* 圆角 */
background-color: #fafafa !important; /* 浅灰色背景 */
}
[data-testid="stFileUploader"]::before {
content: "点击或拖拽文件到此处上传";
position: absolute !important;
top: 50% !important;
left: 50% !important;
transform: translate(-50%, -50%) !important;
font-size: 13px !important; /* 进一步缩小字体 */
color: #666 !important;
font-weight: 500 !important;
z-index: 1 !important;
pointer-events: none !important;
text-align: center !important;
width: 100% !important;
padding: 0 10px !important;
}
[data-testid="stFileUploader"]::after {
content: "支持的文件大小:最大200MB";
position: absolute !important;
bottom: 3px !important; /* 调整位置 */
left: 50% !important;
transform: translateX(-50%) !important;
font-size: 10px !important; /* 进一步缩小字体 */
color: #999 !important;
z-index: 1 !important;
pointer-events: none !important;
}
/* 悬停效果 */
[data-testid="stFileUploader"]:hover {
border-color: #007bff !important;
background-color: #f0f8ff !important;
}
</style>
"""
# 应用自定义样式
st.markdown(custom_css, unsafe_allow_html=True)
st.title("Streamlit文件上传器样式修改测试")
# 文件上传器 - 使用label_visibility隐藏标签
file_uploader = st.file_uploader(
label="文件上传",
help="支持的文件格式:PDF, DOC, DOCX, TXT等",
label_visibility="collapsed" # 隐藏标签但保持可访问性
)
# 显示上传的文件信息
if file_uploader is not None:
st.success(f"文件 '{file_uploader.name}' 上传成功!")
st.write(f"文件大小: {file_uploader.size} bytes")