Cap the number of files that can be uploaded via st.file_uploader?

Hello! :wave:

Is there a way to limit the files that one can upload to a Streamlit app via the st.file_uploader module?

e.g. only allow a user to upload 3 images per session?

Thanks,
Charly

Hey @Charly_Wargnier!

There isn’t any built-in functionality that allows you to limit the number of files, but your question got me thinking, maybe there is a clever bit of coding we can use to make this happen? :thinking:

I’m going to try and find a workaround, will let you know if I find something that works!

Happy Streamlit-ing!
Marisa

There’s nothing to prevent someone from trying to upload a billion items, but if you wanted to force a limit, you could always just read the first X elements from the list of objects. So if people passed 30 items, and you read the first 30, it just wastes their time (though, in the case of Sharing, it could restart the container with too many elements I suppose)

1 Like

Cool, thanks both!

Adding these lines above the file uploader worked! :slight_smile:

(here for a cap of 2 files)

MAX_LINES = 2

if len(multiple_files) > MAX_LINES:

    st.warning(f"Maximum number of files reached. Only the first {MAX_LINES} will be processed.")

    multiple_files = multiple_files[:MAX_LINES]

Charly

1 Like