Unable to update st.file_uploader with a new file

I am writing a script that will update the contents of a variable when a new file uploaded using st.file_uploader(). I am trying to achieve this using the ‘on_change’ function and accessing the new value via the key_field. However, after the first file is successfully uploaded, when I upload a second file, I instead get an error “‘NoneType’ object has no attribute ‘read’”

Below is my code:

def load_new_file():
    with st.spinner("Please wait.. loading the file"):
        new_file = st.session_state["new_file"]
        bytes_data = new_file.read()
        upload_file_to_blob(STORAGE_CONNECTION_STRING, STORAGE_CONTAINER_NAME, "app_data/"+new_file.name, bytes_data)
        st.session_state.document_url = get_blob_sas_url(STORAGE_CONNECTION_STRING, STORAGE_CONTAINER_NAME, "app_data/"+new_file.name)

st.session_state.uploaded_file = st.file_uploader("Choose the PDF file", accept_multiple_files=False, key="new_file", on_change=load_new_file)

I get this error on the line " bytes_data = new_file.read()" everytime I upload a second file and the callback function gets triggered. This doesn’t happen when I upload the file for the first time though. Any idea what could be causing the issue?

I am running the code locally on a Python 3.9 environment with streamlit version 1.28.2

Uploading a new file actually triggers the callback twice:

  1. The first time, the value in session state will be None.
  2. The second time, the value in session state will be the newly uploaded file.

Ah this makes sense. Thanks for clarifying! Do you have any suggestions for how I could solve this issue?

Detect whether new_file is None or not, decide what to do in each case. You don’t want to call new_file.read() when new_file is None.

1 Like

Yes, got it working. Thank you!!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.