file_uploader widget in Streamlit
The file_uploader method is a Streamlit widget that allows users to upload files (such as CSV, Excel, images, or text files) directly through the app interface. Once uploaded, the file can be processed within your Streamlit app using Python.
Syntax
st.file_uploader(label, type=None, accept_multiple_files=False,
key=None, help=None, on_change=None, args=None, kwargs=None) The function has the following parameters:
- label: Text shown above the upload button.
- type: File types allowed (e.g., 'csv', 'xlsx', ['png', 'jpg']).
- accept_multiple_files: If True, allows multiple file uploads.
- key: Unique identifier for the widget.
- help: Tooltip help text.
- on_change: Callback function triggered when a file is uploaded.
- args, kwargs: Extra arguments passed to the callback function.
Example: Upload a CSV file.
Python
# Importing the Streamlit library
import streamlit as st
# Importing the Pandas library
import pandas as pd
# File uploader widget
uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])
# uploaded_file = st.file_uploader("Choose a file")
# Check if file is uploaded
if uploaded_file is not None:
# Read CSV file directly into pandas
df = pd.read_csv(uploaded_file)
st.write("✅ File uploaded successfully!")
# Display the dataframe
st.dataframe(df) Explanation
- When a CSV file is selected, Streamlit loads it into memory.
- pd.read_csv(uploaded_file) reads directly from the in-memory file object.
- st.dataframe(df) displays the uploaded data in an interactive table.