Short answer: Use the “key” parameter of st.file_upload to get a fresh list of uploaded files.
Longer answer:
The way streamlit works, the code runs from start to finish each time. So every time you select a file, the code runs from start to finish. Since you’re uploading multiple files, you need a way to distinguish between selecting multiple files and starting a new list. One way to do this is to use the key field of st.file_upload. You can set it to say a random number. But because the code from start to finish each time, there’s no simple way to know when to generate a new key value.
To fix this, you need to use a button to clear the existing selection and the clicking of the button to generate a new value. You also need to use session state maintenance to not generate a new key unless necessary.
So, you end up with the following code:
import streamlit as st
from random import randint
from .session_state import get_session_state
state = get_session_state()
if not state.widget_key:
state.widget_key = str(randint(1000, 100000000))
uploaded_file = st.file_uploader(
"Choose a file", accept_multiple_files=True, key=state.widget_key)
if st.button('clear uploaded_file'):
state.widget_key = str(randint(1000, 100000000))
state.sync()
Now when the user hits the button to clear the uploaded file, the old list is removed. The session state code I mention is the one from here: https://gist.github.com/okld/0aba4869ba6fdc8d49132e6974e2e662
(Cut and paste everything in that file from class _SessionState to the end of that gist into a file called session_state.py.
Hope this helps,
Dinesh