Search code examples
pythonjupyter-notebookwidgetipythonjupyter

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


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)


Solution

  • 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')