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

Streamlit加载本地上传PDF文件无法显示,求解决方案

问题分析与修复方案

代码里的几个关键问题:

  • 文件上传器配置错误:提示文字写的是“Choose a CSV file”,且未限制文件类型为PDF,不仅会误导用户,还无法过滤非PDF文件,导致后续处理出错。
  • 错误调用读取方法:bytes_data = uploaded_file.read()已经把文件内容读取成了bytes对象,之后又调用bytes_data.read()——bytes类型根本没有read()方法,这会直接抛出AttributeError。就算是文件对象,第一次read后指针会移到文件末尾,第二次read也会得到空内容,导致base64编码为空,PDF自然无法显示。
  • 缺少必要模块导入:代码里用到了base64模块但没有导入,运行时会报NameError。

修正后的代码:

import streamlit as st
import base64

# 配置文件上传器,仅接受PDF文件
uploaded_files = st.file_uploader("Choose PDF files", accept_multiple_files=True, type=["application/pdf"])

for uploaded_file in uploaded_files:
    st.write("filename:", uploaded_file.name)
    # 一次性读取文件的bytes内容
    bytes_data = uploaded_file.read()
    # 直接对bytes内容做base64编码
    base64_pdf = base64.b64encode(bytes_data).decode('utf-8')
    # 构造用于显示PDF的iframe代码
    pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="700" height="1000" type="application/pdf"></iframe>'   
    st.markdown(pdf_display, unsafe_allow_html=True)

额外说明:

  • 如果需要支持多种文件类型,可以把type参数改成["pdf", "csv"]这类列表,但针对PDF显示场景,建议只限制PDF类型,避免不必要的错误。
  • 若上传大文件,iframe渲染可能有性能问题,此时可以考虑用st.download_button让用户下载查看,或者使用第三方库优化PDF显示体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:32:42