首页 > 解决方案 > 从电子应用程序表单的输入中复制选定的文件

问题描述

我有这个表格

<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

标签: javascripthtmlnode.jsnpmelectron

解决方案


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

看来您是从renderer进程中调用它的。因此,您需要使用electron.remote才能访问该dialog模块(如您上面使用的代码示例所示)。

值得花时间阅读其中的过程mainrenderer过程Electron——它们是您将反复遇到的基本概念,它们在IPC 消息传递中尤为重要


推荐阅读