python-eel / Eel

A little Python library for making simple Electron-like HTML/JS GUI apps
MIT License
6.5k stars 592 forks source link

How can I upload a file to frontend and handle it on the backend? #613

Open nh916 opened 2 years ago

nh916 commented 2 years ago

Describe the problem I want to be able to upload a file from the frontend html side and catch it on the backend with python eel and do calculations on the file. How can I accomplish this?

For example the user uploads a csv file to the frontend to the python eel backend, so I can do some calculations on it?

maRT-sk commented 2 years ago

I use tkinter and alpinejs to "upload files":

hello.py:

import eel
import tkinter
from tkinter import filedialog as fd

eel.init('web')

@eel.expose
def choose_file():
    tkinter.Tk().withdraw()
    filename = fd.askopenfilename()
    return filename

eel.start('hello.html', size=(300, 200))

web/hello.html:

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Hello, World!</title>
  <script type="text/javascript" src="/eel.js"></script>
  <script src="//unpkg.com/alpinejs" defer></script>
</head>

<body x-data="{file:null}">
<div>
  <button x-on:click="file = eel.choose_file()">Choose a file</button>
  <span x-text="file == null ? 'No file chosen': file"></span>
</div>
</body>

</html>
chandsharma commented 2 years ago

expose python function using eel python function will receive byte string as argument

def get_file_from_frontend(byte_string):
    #decode byte_string back to original
    pass

Now in front-end you call this function and pass byte_string encoded file

eel.get_file_from_frontend(byte_string);