streamlit使用技巧

实现上传PDF并显示#

## 上传并预览(1M以内才可预览)
def upload_Pre():
    file = st.file_uploader("选择待上传的PDF文件", type=['pdf'])
    if st.button("点击"):
        if file is not None:
            with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
                fp = Path(tmp_file.name)
                fp.write_bytes(file.getvalue())
                with open(tmp_file.name, "rb") as f:
                    base64_pdf = base64.b64encode(f.read()).decode('utf-8')
                pdf_display = f'<embed src="data:application/pdf;base64,{base64_pdf}" ' \
                              f'width="800" height="1000" type="application/pdf">'
                st.markdown(pdf_display, unsafe_allow_html=True)

实现上传(多个)不同类型文件并保存#

# 上传文件
def upload_Save():
    # 创建一个文件夹用于保存上传的文件(若存在则清空,若不存在,则新建)
    dirs = 'uploads'
    if not os.path.exists(dirs):
        os.makedirs(dirs)
    else:
        shutil.rmtree(dirs)
        os.makedirs(dirs)
    # 选择文件
    uploaded_files = st.file_uploader("请选择情报文件:",accept_multiple_files =True, type=["pdf","txt","docx"])
    # 保存文件
    if uploaded_files:
        for uploaded_file in uploaded_files:
            file_contents = uploaded_file.getvalue()
            file_path = os.path.join(dirs, uploaded_file.name)
            # 将文件保存到本地文件系统
            with open(file_path, "wb") as f:
                f.write(file_contents)
            # 获取文件路径
            st.write(f"文件地址: {file_path}")
        return os.path.join(os.path.dirname(os.path.abspath(__file__)),dirs)

实现下载文件按钮#

# 下载文件
def download_res(file_path):
    if file_path:
        # 下载
        with open(file_path, "rb") as file:
            btn = st.download_button(
                label="📥 下载文件",
                data=file,
                file_name=file_path.split('/')[-1],
                mime="txt"
            )
    else:
        print("无文件可下载!")

实现触发提示#

def prompt_change():
	text = f"已切换为 {prompt_template_name} 模板。"
	st.toast(text)

prompt_template_select = st.selectbox(
	"请选择Prompt模板:",
	prompt_templates_kb_list,
	index=0,
	on_change=prompt_change,
	key="prompt_template_select",
)

作者:Hang Shao

出处:https://www.cnblogs.com/pam-sh/p/17957983

版权:本作品采用「知识共享」许可协议进行许可。

声明:欢迎交流! 原文链接 ,如有问题,可邮件(mir_soh@163.com)咨询.

posted @   PamShao  阅读(1665)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu