1 2 File Uploader Explained
Key Concepts
- st.file_uploader: A widget that allows users to upload files.
- File Types: The types of files that can be uploaded.
- File Handling: How to process and use the uploaded files.
st.file_uploader
st.file_uploader
is a Streamlit widget that provides a file upload interface. Users can select and upload files from their local system. This widget is particularly useful for applications that require user-provided data, such as CSV files for data analysis or image files for image processing.
File Types
The st.file_uploader
function accepts a parameter called type
that specifies the types of files that can be uploaded. This parameter can be a string or a list of strings representing file extensions (e.g., "png", "jpg", "csv"). By specifying the file types, you can restrict the upload to only those file types that your application can handle.
File Handling
Once a file is uploaded, it is stored as a BytesIO
object in memory. You can then read and process the file using Python's standard file handling methods. For example, if the uploaded file is a CSV, you can use the pandas
library to read and manipulate the data.
Examples
Here are some examples to illustrate the use of st.file_uploader
:
import streamlit as st import pandas as pd st.title("File Uploader Example") # Basic file uploader uploaded_file = st.file_uploader("Choose a file") if uploaded_file is not None: st.write(f"File name: {uploaded_file.name}") st.write(f"File size: {uploaded_file.size} bytes") # File uploader with specified file types uploaded_csv = st.file_uploader("Upload a CSV file", type=["csv"]) if uploaded_csv is not None: df = pd.read_csv(uploaded_csv) st.write(df) # File uploader for image files uploaded_image = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"]) if uploaded_image is not None: st.image(uploaded_image, caption="Uploaded Image", use_column_width=True)
Analogies
Think of st.file_uploader
as a digital version of a file drop box. Users can drop their files into this box, and your application can then process these files. The file types parameter is like setting rules for what kind of files can be dropped into the box, ensuring that only appropriate files are accepted.
By mastering st.file_uploader
, you can enhance your Streamlit applications by allowing users to upload and interact with their own data, making your apps more versatile and user-friendly.