javascriptpythonhtmleel

How to pass selected file path to python script via javascript


I'm using eel to create a simple but clean GUI to my project. In this project, I have a custom database which I pickle/update/unpickle when needed. From local webserver, I select the file and click the submit button. Then I pass the file directory to later read in python script. The structure I have is as follows;

HTML

I have two simple elements, one button and one input

<input type="file" id="file-upload">
<input class="btn btn-success" type="submit" onClick="get_input_directory()" value="Send">

JS

function get_input_directory() {
    var data = document.getElementById("file-uploader").value
    eel.get_input(data)
}

Python

And for the moment I just print the directory If I got it right.

@eel.expose
def get_input(data):
    print(data)

And what I planned to do later was to use the script down to unpickle database into my program:

with open(file_dir, "rb") as f:
    mdl = pickle.load(f)
    return mdl

But my database file is printed as:

C:/fakepath/database.file

I searched the web and found out that this is a security measure that browser implemented but I tried FileReader method to pass the file directly into the unpickling function but that also failed saying that no such file exists.

What should I use for this problem, or is there a way to pass the directory into the python script which would be much easier since the backend is pretty much done for project. Any help is appreciated. Thanks in advance!


Solution

  • This has to do with JS not having full exist to your computer. Best to do is add the file handler in python/eel. Because python does has full access to the path of your computer:

    @eel.expose
    def btn_ResimyoluClick():
        root = Tk()
        root.withdraw()
        root.wm_attributes('-topmost', 1)
        folder = filedialog.askdirectory()
        return folder
    

    Copied from: https://github.com/samuelhwilliams/Eel/issues/86