javascript - 从电子应用程序表单的输入中复制选定的文件
问题描述
我有这个表格
<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)
看来您是从renderer
进程中调用它的。因此,您需要使用electron.remote
才能访问该dialog
模块(如您上面使用的代码示例所示)。
值得花时间阅读其中的过程main
和renderer
过程Electron
——它们是您将反复遇到的基本概念,它们在IPC 消息传递中尤为重要
推荐阅读
- python - psycopg2:如何将数据从 Python 应用程序添加到 Postgresql
- java - 为什么 saveAll() 总是插入数据而不是更新数据?
- arrays - 读取浮点数的二进制文件并将它们放入数组中
- amazon-web-services - 为什么我的 AWS S3 策略不会仅限制某些 IP 地址的访问?
- python - mplfinance 图未正确显示时间值
- reactjs - 在reactjs nextjs中将url重定向到www作为服务器端301
- python - 在 Python 中调用变量(本地与全局)
- c# - 如何在控制器中使用 IdentityServer4 获取 ASP.NET 核心中的当前用户?
- r - 在 R 中使用 plot_grid 和 get_legend 的困难
- terminal - 如何更改路径?