實現上傳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("無文件可下載!")