3

I'm trying to build a web app with NiceGUI where the user can upload a file, and then be shown the contents of the file (or a message, any text as a label element really). It works fine, except that when I upload a second file, it keeps the old text (which actually makes sense when I think about it), and even if I refresh the page the old text is still there.

This is the code I wrote, and I was expecting that if the user refreshed the page, the labels created by handle_upload would disappear (similar to how the file upload element refreshes on page refresh and no longer shows the previously uploaded files).

from nicegui import ui, events
import os

ui.label("Upload File")
ui.label('(Drag and drop into the box below, or use the "+" button to select a file)')


def handle_upload(file: events.UploadEventArguments) -> None:
    ui.notify(f"uploaded {file.name} to {os.getcwd()}")
    data = file.content.read()
    with open(file.name, "wb") as f:
        f.write(data)
    lines = [line for line in data.splitlines() if line.strip()]
    ui.label("Lines uploaded:")
    for line in lines:
        ui.label(line.decode())

ui.upload(on_upload=handle_upload, auto_upload=True).classes("max-w-full")


ui.run(title="Submit File")

nopori
  • 76
  • 5

1 Answers1

2

Yes, calling ui.label creates a new label and adds it to the page. To replace elements like a label with new ones, you can use a container and clear it before adding new elements. In the following example the container output is of type ui.column and is filled with the "Lines uploaded:" label as well as the file content:

def handle_upload(file: events.UploadEventArguments) -> None:
    data = file.content.read()
    lines = [line for line in data.splitlines() if line.strip()]
    output.clear()
    with output:
        ui.label('Lines uploaded:')
        for line in lines:
            ui.label(line.decode())

ui.upload(on_upload=handle_upload, auto_upload=True)
output = ui.column()
Falko
  • 17,076
  • 13
  • 60
  • 105