最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Python3JS - How do I handle local file uploads with eel? - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Dec 2, 2019 at 16:44 NootakuNootaku 4196 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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.

发布评论

评论列表(0)

  1. 暂无评论