Search code examples
pythonfile-uploadstreamlit

Streamlit image/file upload to deta drive


This was also on streamlit discussion

I want to help others who are facing the same problem!


Solution

  • You can directly use the bytes data. Here is an example code uploading a single file for demo purposes.

    """Upload image file from disk to deta using streamlit.
    
    References:
    
      streamlit:
        https://docs.streamlit.io/library/api-reference/widgets/st.file_uploader
    
      deta:
        https://docs.deta.sh/docs/drive/sdk#put
    """
    
    import streamlit as st
    from deta import Deta
    
    # Initialize a project with project key from deta.
    project = Deta("your_project_key")
    
    # Define the drive to store the files.
    drive_name = 'project_2_drive_1'
    drive = project.Drive(drive_name)
    
    # Initialize a streamlit file uploader widget.
    uploaded_file = st.file_uploader("Choose a file")
    
    # If user attempts to upload a file.
    if uploaded_file is not None:
        bytes_data = uploaded_file.getvalue()
    
        # Show the image filename and image.
        st.write(f'filename: {uploaded_file.name}')
        st.image(bytes_data)
    
        # Upload the image to deta using put with filename and data.
        drive.put(uploaded_file.name, data=bytes_data)