streamlit使用技巧

发布时间 2024-01-11 10:27:12作者: PamShao

实现上传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("无文件可下载!")