Search code examples
pythonfilesizestreamlit

storing file size of a file in variable Streamlit


I am trying to create a file size restriction in streamlit. For this I need to get the uploaded file size of a into a varible.

In a simple python script i was able to use the following function to get file size.

os.path.getsize("filename.mp3")

But I am unable to do it in streamlit app.


Solution

  • In streamlit you can use the file uploader widget st.file_uploader in order to upload a file:

    uploaded_file = st.file_uploader("Choose a file")
    

    To get the size of the uploaded file we need two steps:

    1. get the uploaded file bytes using getvalue():

       bytes_data = uploaded_file.getvalue()
      
    2. get the size by using the python built in len() function on the bytes:

       file_size = len(bytes_data)
      

    All together:

    import streamlit as st
    
    # upload file
    uploaded_file = st.file_uploader("Choose a file")
    if uploaded_file is not None:
        # To read file as bytes:
        bytes_data = uploaded_file.getvalue()
        # get file size
        file_size  = len(bytes_data)
    

    Also a note about file size, in Streamlit by default, uploaded files are limited to 200MB. You can configure this using the server.maxUploadSize config option. For more you can read in there documentation