Jelajahi Sumber

add demo "download text as file"

Rodja Trappe 1 tahun lalu
induk
melakukan
f4787ac7ec
2 mengubah file dengan 30 tambahan dan 0 penghapusan
  1. 29 0
      examples/download_text_as_file/main.py
  2. 1 0
      main.py

+ 29 - 0
examples/download_text_as_file/main.py

@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+from io import StringIO
+from uuid import uuid4
+
+from fastapi.responses import StreamingResponse
+
+from nicegui import Client, app, ui
+
+
+@ui.page('/')
+async def index(client: Client):
+    download_path = f"/download/{uuid4()}.txt"
+
+    @app.get(download_path)
+    async def download():
+        # create a file-like object from the string
+        string_io = StringIO(text_entry.value)
+        return StreamingResponse(
+            string_io, media_type="text/plain",
+            headers={'Content-Disposition': 'attachment; filename=download.txt', }
+        )
+
+    text_entry = ui.textarea(value="hello world")
+    ui.button("Download", on_click=lambda: ui.download(download_path))
+    # cleanup the download route after the client disconnected
+    await client.disconnected()
+    app.routes[:] = [route for route in app.routes if route.path != download_path]
+
+ui.run()

+ 1 - 0
main.py

@@ -312,6 +312,7 @@ async def index_page(client: Client) -> None:
             example_link('Pandas DataFrame', 'displays an editable [pandas](https://pandas.pydata.org) DataFrame')
             example_link('Lightbox', 'A thumbnail gallery where each image can be clicked to enlarge')
             example_link('ROS2', 'Using NiceGUI as web interface for a ROS2 robot')
+            example_link('Download Text as File', 'providing in-memory data like strings as file download')
 
     with ui.row().classes('dark-box min-h-screen mt-16'):
         link_target('why')