3

I'm trying to implement a download button in jupyter notebook (IPython). I know that button widget do exists in jupyter like below.

from ipywidgets import Button

...

btn_download = widgets.Button(
    description='Download',
    button_style='', # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Download',
    icon='download',
    layout=button_layout )

# Then implement download in on_click 
def on_button_download_clicked(b):
    # Handle download using urlopen
    filedata = urllib.request.urlopen(r'file://' + filepath)
    datatowrite = filedata.read()
    with open("download.fid", 'wb') as f:  
        f.write(datatowrite)

# Register callback
btn_download.on_click(on_button_download_clicked)

However, this does not seem to work. I have tried few other methods like using urlretrieve and still won't work.

I am also aware that solution such as using ipython.display.FileLink exists, but I want to have it in form of button.

Is there any workaround in this?

Darren Christopher
  • 3,893
  • 4
  • 20
  • 37
  • Can you describe more about how it does not work? What kind of errors do you receive when you try to click the button? – ac24 Jul 02 '19 at 07:08
  • @ac24 I do not encounter any error, it just doesn't do anything when I clicked. What this code does, however, is writing the `datatowrite` into `download.fid` in the server alongside the notebook. I am not sure how to pass the `datatowrite` into client (browser) connecting to the notebook. Do you have any solution for this? – Darren Christopher Jul 02 '19 at 23:47
  • Your function has the button instance as the first argument. You could always assign the `datawrite` variable to the button instance in the `on_button_download_clicked()` e.g. `b.file = datawrite`. Then the file should be available. – ac24 Jul 03 '19 at 06:41
  • Have a look at related question https://stackoverflow.com/questions/61708701/how-to-download-a-file-using-ipywidget-button – Temak Feb 07 '23 at 23:48

1 Answers1

2

Solara has a FileDownload component that can be used for this.

import solara

filepath = "/Users/maartenbreddels/beach.jpeg"
data = open(filepath, "rb").read()
solara.FileDownload(data=data, label="Download image", filename="image.jpeg")

This looks like:

enter image description here

If you need this embedded in a ipywidget VBox, or HBox, use the .widget method:

import ipywidgets as widgets
widgets.VBox([
    solara.FileDownload.widget(data=data, label="Download image", filename="image.jpeg")
])
Maarten Breddels
  • 1,344
  • 10
  • 12