Search code examples
javascripthtmlfile-uploadeel

Python3 / JS - How do I handle local file uploads with eel?


I am currently working on a local Electron-like software with Eel.

This software is intended to be bundled as a standalone Windows application that needs to run on the user's local machine.

Within this software I want to be able to select and work on local files with at Python backend. To access the file, I use an HTML <form> with a <input type='file' />.

I'm wondering how I should handle the upload of local files within this framework as, unlike electron there is no dialog.showOpenDialog() function available in vanilla JavaScript.

The following question helps another user with Electron, but I'm searching for a workaround in vanilla ES6.

Thanks in advance


Solution

  • After fiddling around with JS and HTML5 File API (and failing very poorly to get the expected result), I remembered that I'm a Python guy.

    The simplest solution to this problem that came to my mind is to let Python handle the File management. So instead of having an HTML <input type='file'>, I'm creating a button with an onclick JS function:

    <button type="button" onclick="getPathToFile()">Select File</button>
    
    
    <script type="text/javascript">
        function getPathToFile() {
            eel.pythonFunction()(r => console.log(r));
        };
    </script>
    

    Meanwhile I let Python handle the file dialog on the backend:

    import wx
    import eel
    
    @eel.expose
    def pythonFunction(wildcard="*"):
        app = wx.App(None)
        style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
        dialog = wx.FileDialog(None, 'Open', wildcard=wildcard, style=style)
        if dialog.ShowModal() == wx.ID_OK:
            path = dialog.GetPath()
        else:
            path = None
        dialog.Destroy()
        return path
    

    In JavaScript's console you then get [1] path/to/selected/file.

    This method also allows you to execute actions on the file as if you were in Python (parse, save, modify, ...) and to display the information using HTML / CSS / JavaScript GUI.
    Pretty neat.