javascript - 从 Electron 应用程序表单的输入中复制选定的文件

标签 javascript html node.js npm electron

我有这个表格

<form>
  <input type="file" name="idp" id="idp" onchange="uploadFiles();"/>
</form>

当用户选择一张图片时,我需要将其复制到指定的文件夹并将其全名存储到变量中以将其保存到数据库中。

我尝试过这段代码:

const electron = require('electron');
const { dialog } = electron;    // electron.remote; (if in renderer process)
const fs = require('fs');       // module that interacts with the file system
const path = require("path"); 
function uploadFiles(){
    // opens a window to choose file
    dialog.showOpenDialog({properties: ['openFile']}).then(result => {

        // checks if window was closed
        if (result.canceled) {
            console.log("No file selected!")
        } else {

            // get first element in array which is path to file selected
            const filePath = result.filePaths[0];

            // get file name
            const fileName = path.basename(filePath);

            // path to app data + fileName = "C:\Users\John\AppData\Roaming\app_name\picture.png"
            imgFolderPath = path.join(app.getPath('userData'), fileName);

            // copy file from original location to app data folder
            fs.copyFile(filePath, imgFolderPath, (err) => {
                if (err) throw err;
                console.log(fileName + ' uploaded.');
            });
        }
    });
};

它在控制台上给我这个错误消息:

Uncaught TypeError: Cannot read property 'showOpenDialog' of undefined
    at uploadFiles 
    at HTMLInputElement.onchange

最佳答案

const { dialog } = electron;    // electron.remote; (if in renderer process)

看来您正在从渲染器进程中调用此函数。因此,您需要使用 Electron.remote 才能访问dialog 模块(如上面使用的代码示例所示)。

值得花时间阅读 Electron 中的mainrenderer 进程 - 它们是您将遇到的基本概念以及它们在 IPC messaging 中尤其重要

关于javascript - 从 Electron 应用程序表单的输入中复制选定的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60679023/

相关文章:

html - Angular2嵌入对象类型绑定(bind)不起作用

html - Materialize carousel-item 不继承默认属性

JavaScript - 为什么我们必须从自调用函数返回一个函数?

javascript - 为什么 Formidable `form.parse` 回调没有在 Express 中运行?

onmouseover() 的 JavaScript 转换没有在 onmouseout() 事件中转换回我想要的方式

javascript - 如何在 Visual Studio 代码中与文件一起导入扩展名?

javascript - 带有授权 header 的 HTML 文件上传

Javascript 表单未按预期在 IE 上提交

html - CSS:填充/边距问题。是什么导致了这种惊人的变化?

mysql - 使用 mysql 和 knex 将 SELECT COUNT 保存到变量中