Can I define an action on file upload when using ipywidgets FileUpload widget

Question:

I want to create an event off the uploading of a file with widgets.FileUpload same as I would do with an widgets.Button using the .on_click(some_function). Is there a way to do something like this

import ipywidgets as widgets

def do_something_with_file(fu):

    content = fu.data[0].decode('utf-8') 
    # doing something with the file content and get some string output
    return 'some string'

str_file_upload = widgets.FileUpload(accept='.txt', multiple=False)
str_file_upload.on_upload(do_something_with_file)

Asked By: Dean

||

Answers:

You can observe the change in _counter

Example:

from ipywidgets import widgets
uploader = widgets.FileUpload()
display(uploader)

def on_upload_change(change):
    print(change)

uploader.observe(on_upload_change, names='_counter')
Answered By: Davide De Marchi

The above answer is not working anymore, with ipywidgets version >= 8.0.2:

TypeError: No such trait: FileUpload._counter

Instead observe the change in value:

Example:

from ipywidgets import widgets
uploader = widgets.FileUpload()
label = widgets.Label("")

def on_upload_change(change):
    label.value = "Loaded"

uploader.observe(on_upload_change, names='value')

display(uploader, label)
Answered By: Tom Tom