我有一个带有侧栏的流光应用程序,它由一个带有两个值的单选按钮组成:A& B。两个A&B都使用st.file_uploadeer()将视频上传到应用程序。但是,当我在A和B之间切换时,上传的视频会因为页面重新加载而丢失。除非用户特别更改上传的文件,否则如何保留上传的视频?我认为可以使用st.file_uploader()函数的会话状态或st.file_uploader()回调来完成,但我无法弄清楚如何做到这一点。
import streamlit as st
val=st.sidebar.radio('Pick one!',['A','B'])
def upload_video(key):
#Let's user upload a file from their local computer
uploaded_file = st.file_uploader(
'Choose a file', key=key)
if uploaded_file is not None:
# gets the uploaded video file in bytes
bytes_data = uploaded_file.getvalue()
file_details = {'Filename: ': uploaded_file.name,
'Filetype: ': uploaded_file.type,
'Filesize: ': uploaded_file.size}
# st.write('FILE DETAILS: \n', file_details)
st.write('\n\nUploaded video file')
# displays the video file
st.video(uploaded_file)
# saves the uploaded video file
with open(uploaded_file.name, "wb") as vid:
vid.write(bytes_data)
return uploaded_file.name
# if the user presses "A" in the radio button
if val=="A":
upload_video("A")
# if the user presses "B" in the radio button
if val=='B':
upload_video("B")
我现在已经添加了代码片段,当我按下侧边栏中的B按钮,然后导航回A时,上传的视频将被清除。如何解决这个问题?另外,这是我第一次堆叠溢出的帖子,我为问问题时的任何错误道歉。任何帮助都将不胜感激。
发布于 2022-01-23 13:08:33
你可以这样写:
import streamlit as st
val = st.sidebar.radio('Pick one!', ['A', 'B'])
def upload_video(key):
st.write('key : ', key)
if 'video_path' not in st.session_state:
st.session_state['video_path'] = None
# Let's user upload a file from their local computer
uploaded_file = st.file_uploader(
'Choose a file', key=key)
if st.session_state['video_path'] != None:
agree = st.checkbox(
'Previous file found! Do you want to use previous video file?')
if agree:
vid = open(st.session_state['video_path'], 'rb')
video_bytes = vid.read()
st.video(video_bytes)
return st.session_state['video_path']
if uploaded_file is not None:
# gets the uploaded video file in bytes
bytes_data = uploaded_file.getvalue()
file_details = {'Filename: ': uploaded_file.name,
'Filetype: ': uploaded_file.type,
'Filesize: ': uploaded_file.size}
# st.write('FILE DETAILS: \n', file_details)
st.session_state['video_path'] = uploaded_file.name
st.write(st.session_state['video_path'])
st.write('\n\nUploaded video file')
# displays the video file
st.video(uploaded_file)
# saves the uploaded video file
with open(uploaded_file.name, "wb") as vid:
vid.write(bytes_data)
return uploaded_file.name
# if the user presses "A" in the radio button
if val == "A":
upload_video("A")
# if the user presses "B" in the radio button
if val == 'B':
upload_video("B")
在手动刷新页面之前,视频文件仍然存在。
https://stackoverflow.com/questions/70648239
复制相似问题