How to add a download button in Streamlit

In this recipe, we will learn how to add a download button in Streamlit. We will also take a look at a Streamlit web application that consists of a download button.

Recipe Objective: How to add a download button in streamlit?

Streamlit allows you to add interactivity directly into the app with the help of widgets. You can add a download button in Streamlit using "st.download_button". It returns a boolean value.

 Syntax: st.download_button(label, data, file_name, mime, key, help, on_click, args, kwargs)
 Parameters:
   label -> A simple label that explains what this button is for
   data -> The content of the file that the user is about to download. For caching methods to prevent recomputing this data unnecessarily, see the example below.
   file_name -> The name of the file to be downloaded as (eg: "data.csv"). The name will be generated automatically if none is provided.
   mime-> The data's MIME type. Defaults to "text/plain" or "application/octet-stream" if None is specified.
   key -> An optional string or int to be used as a unique key for the button. If omitted, a key will be generated for the button based on its content. Multiple buttons i.e. multiple widgets of same types cannot share the same key.
   help -> An optional tooltip that is be displayed when hovered on the button
   on_click -> An optional callback invoked when the button is clicked
   args -> An optional tuple of args that can be passed to the callback
   kwargs -> An optional dictionary of kwargs that can be passed to the callback

Code:

#importing required libraries
import streamlit as st

#creating a sample dataframe to download
df = pd.DataFrame(np.random.randn(800, 2) / [50, 50] + [19.07, 72.87],columns=['latitude', 'longitude'])

#function to convert any dataframe to a csv file
@st.cache
def convert_df(df):
# IMPORTANT: Cache the conversion to prevent computation on every rerun
return df.to_csv().encode('utf-8')

#converting the sample dataframe
csv = convert_df(df)

#adding a download button to download csv file
st.download_button(
label="Download data as CSV",
data=csv,
file_name='sample_df.csv',
mime='text/csv',
)

#defining sample text that to download
text_content = "Sample text"

#adding a download button to download text
st.download_button('Download sample text', text_content)

#adding a download button to download an image
with open("imagename.png", "rb") as file:
btn = st.download_button(
label="Download image",
data=file,
file_name="imagename.png",
mime="image/png"
)

To run the app, either create an appname.py file with the above code using any text editor, or if you are using a jupyter notebook, you need to download your .ipynb notebook as a Python (.py) file and run the same using the "streamlit run appname.py" command. Once you run the command, the app will automatically open in your default browser.

What Users are saying..

profile image

Ray han

Tech Leader | Stanford / Yale University
linkedin profile url

I think that they are fantastic. I attended Yale and Stanford and have worked at Honeywell,Oracle, and Arthur Andersen(Accenture) in the US. I have taken Big Data and Hadoop,NoSQL, Spark, Hadoop... Read More

Relevant Projects

Census Income Data Set Project-Predict Adult Census Income
Use the Adult Income dataset to predict whether income exceeds 50K yr based oncensus data.

Linear Regression Model Project in Python for Beginners Part 2
Machine Learning Linear Regression Project for Beginners in Python to Build a Multiple Linear Regression Model on Soccer Player Dataset.

Learn to Build a Polynomial Regression Model from Scratch
In this Machine Learning Regression project, you will learn to build a polynomial regression model to predict points scored by the sports team.

Learn to Build a Siamese Neural Network for Image Similarity
In this Deep Learning Project, you will learn how to build a siamese neural network with Keras and Tensorflow for Image Similarity.

Time Series Python Project using Greykite and Neural Prophet
In this time series project, you will forecast Walmart sales over time using the powerful, fast, and flexible time series forecasting library Greykite that helps automate time series problems.

Build a Speech-Text Transcriptor with Nvidia Quartznet Model
In this Deep Learning Project, you will leverage transfer learning from Nvidia QuartzNet pre-trained models to develop a speech-to-text transcriptor.

Tensorflow Transfer Learning Model for Image Classification
Image Classification Project - Build an Image Classification Model on a Dataset of T-Shirt Images for Binary Classification

Build a Autoregressive and Moving Average Time Series Model
In this time series project, you will learn to build Autoregressive and Moving Average Time Series Models to forecast future readings, optimize performance, and harness the power of predictive analytics for sensor data.

Time Series Analysis with Facebook Prophet Python and Cesium
Time Series Analysis Project - Use the Facebook Prophet and Cesium Open Source Library for Time Series Forecasting in Python

Mastering A/B Testing: A Practical Guide for Production
In this A/B Testing for Machine Learning Project, you will gain hands-on experience in conducting A/B tests, analyzing statistical significance, and understanding the challenges of building a solution for A/B testing in a production environment.