Download processed data from Kino.listen

Hey, Livebook devs!

I’m listening to form submissions in a Livebook with:


Kino.listen(crawler_form, 
fn event ->
   json_output = 
      Crawler.test_output(event.data) 
      |> Jason.encode!()
   IO.inspect(json_output)

end)

I want to write json_output to a file and make the file available for download, like in Kino.Download.new. How do I pass data from Kino.listen to Kino.Download.new?

Kino.listen(crawler_form, 
fn event ->
   # Create a function that generates the JSON output
   content_fun = fn -> 
     Crawler.test_output(event.data) 
     |> Jason.encode!() 
   end

   # Create the download button
   Kino.Download.new(content_fun, filename: "output.json")
end)

Hey @aar2dee2! Here’s an example:

# Form -> download

```elixir
Mix.install([
  {:kino, "~> 0.10.0"}
])
```

## Section

```elixir
form =
  Kino.Control.form(
    [text: Kino.Input.textarea("Content")],
    submit: "Submit"
  )
```

```elixir
frame = Kino.Frame.new()
```

```elixir
Kino.listen(form, fn event ->
  content_fun = fn ->
    event.data.text
  end

  Kino.Frame.render(frame, Kino.Download.new(content_fun), to: event.origin)
end)
```

Note that to: event.origin makes the download button only available to the user who submitted the form, you can omit it, if the button should be available to everyone.

4 Likes

Thank you so much!!

1 Like