我有这个表格
<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
中的main
和 renderer
进程 - 它们是您将遇到的基本概念以及它们在 IPC messaging 中尤其重要
关于javascript - 从 Electron 应用程序表单的输入中复制选定的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60679023/