NiceGUI is a Python library that lets you build web-based user interfaces (UIs). It has a gentle learning curve, making it great for beginners, while also offering advanced customization for experienced users. Here are some key points about NiceGUI.
In this tutorial, we will learn how to handle file uploads in NiceGUI Python. Let start with how to use the file upload widget in NiceGUI
The ui.uploads is used to work with file uploads, it takes in a callback function or lambda function for the on_uploads which determines what should be done when a file is uploaded
The function usually takes in an UploadEventArguments from nicegui events in order to handle the uploaded file and then from there you can process it respectively.
from nicegui import ui ,events
def handle_uploads(e: events.UploadEventArguments ):
text = e.content.read().decode("utf-8")
markdown_data.set_content(text)
ui.upload(on_upload=handle_uploads).props("accept=.md").classes("max-w-full")
## show the content
markdown_data = ui.markdown()
ui.run(port=8002)
You can use the `.props(“accept=”)` to restrict the file type your want to accept and automatically allow for selection for uploads.
#all files
ui.upload(on_upload=handle_uploads)
# for markdown
ui.upload(on_upload=handle_uploads).props("accept=.md").classes("max-w-full")
# for csv
ui.upload(on_upload=handle_uploads).props("accept=.csv").classes("max-w-full")
The events.UploadEventArguments offers the option of being able to read the file content. With this you can use any file processing library or function to display the uploaded content by connecting it to a ui element.
def handle_uploads(e: events.UploadEventArguments ):
text = e.content.read().decode("utf-8")
markdown_data.set_content(text)
The easiest way to read csv files is via pandas, however Pandas.read_csv() takes in a file IO hence we will need to convert the content read into an IO format using StringIO .Below is a function to handle csv file upload.
from nicegui import ui ,events
import pandas as pd
from io import StringIO
def csv_file_handler(e: events.UploadEventArguments):
with StringIO(e.content.read().decode("utf-8")) as f:
df = pd.read_csv(f)
Now let us combine all to both read csv file and display it inside a table
from nicegui import ui ,events
import pandas as pd
from io import StringIO
def csv_file_handler(e: events.UploadEventArguments):
with StringIO(e.content.read().decode("utf-8")) as f:
df = pd.read_csv(f)
# show the content
ui.table(columns=[{"name":col, "label":col, "field":col } for col in df.columns],
rows=df.to_dict(orient="records"), pagination={"rowsPerPage": 10})
ui.upload(on_upload=csv_file_handler).props("accept=.csv").classes("max-w-full")
ui.run(port=8002)
We have seen how to handle file uploads using NiceGUI.
Happy Coding!!!