How to Clear Uploaded File in st.file_uploader

Hi ,

I am using file_uploader function to upload multiple files. Multiple file getting uploaded perfectly but these files gets retained and when I try to add new set of files, new files just get appended to the already uploaded files. This issue persists even after clearing the cache. Attaches screenshots for the same.
First upload:


Second upload:

Files just keep appending even after clearing the cache.

uploaded_files = st.file_uploader("Choose Files ", type=['txt'], accept_multiple_files=True, key="dc_mfup_1")
for uploaded_file in uploaded_files:
    bytes_data = uploaded_file.read()

Is there a solution to address this issue? Thanks.

Hi @Chakra I’m facing the same issue here. Can you kindly let me know if you managed to solve this? Thanksss

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

1 Like