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

Abhinav Agarwal

Graduate Student at Northwestern University
linkedin profile url

I come from Northwestern University, which is ranked 9th in the US. Although the high-quality academics at school taught me all the basics I needed, obtaining practical experience was a challenge.... Read More

Relevant Projects

Build a Multi Touch Attribution Machine Learning Model in Python
Identifying the ROI on marketing campaigns is an essential KPI for any business. In this ML project, you will learn to build a Multi Touch Attribution Model in Python to identify the ROI of various marketing efforts and their impact on conversions or sales..

PyTorch Project to Build a LSTM Text Classification Model
In this PyTorch Project you will learn how to build an LSTM Text Classification model for Classifying the Reviews of an App .

Demand prediction of driver availability using multistep time series analysis
In this supervised learning machine learning project, you will predict the availability of a driver in a specific area by using multi step time series analysis.

Build Piecewise and Spline Regression Models in Python
In this Regression Project, you will learn how to build a piecewise and spline regression model from scratch in Python to predict the points scored by a sports team.

AWS MLOps Project to Deploy Multiple Linear Regression Model
Build and Deploy a Multiple Linear Regression Model in Python on AWS

Build a CNN Model with PyTorch for Image Classification
In this deep learning project, you will learn how to build an Image Classification Model using PyTorch CNN

Hands-On Approach to Regression Discontinuity Design Python
In this machine learning project, you will learn to implement Regression Discontinuity Design Example in Python to determine the effect of age on Mortality Rate in Python.

BERT Text Classification using DistilBERT and ALBERT Models
This Project Explains how to perform Text Classification using ALBERT and DistilBERT

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

Walmart Sales Forecasting Data Science Project
Data Science Project in R-Predict the sales for each department using historical markdown data from the Walmart dataset containing data of 45 Walmart stores.