How to download file in streamlit

I wrote a generic downloader that should work for any type of file that’s stored on your disk.
Though some developers may whine that this is not the right/optimal thing to do, well, who cares :wink:
So here you go.

The function:

import os
import base64
def get_binary_file_downloader_html(bin_file, file_label='File'):
    with open(bin_file, 'rb') as f:
        data = f.read()
    bin_str = base64.b64encode(data).decode()
    href = f'<a href="data:application/octet-stream;base64,{bin_str}" download="{os.path.basename(bin_file)}">Download {file_label}</a>'
    return href

Usage:

st.markdown(get_binary_file_downloader_html('photo.jpg', 'Picture'), unsafe_allow_html=True)
st.markdown(get_binary_file_downloader_html('data.csv', 'My Data'), unsafe_allow_html=True)
st.markdown(get_binary_file_downloader_html('2g1c.mp4', 'Video'), unsafe_allow_html=True)
19 Likes