Electron选择文件文件夹对话框非原创传播
文章转载自:https://www.jianshu.com/p/e71...,感谢文章作者,成功完成选择文件夹 的功能 1.第一种方法,纯js代码其原理是:利用input标签的file类别,打开选择文件对话框通过input标签的change事件,将选择的文件返回。为了使每次选择的文件都得到更新,在input对象用完后每次都移除出html中,下次使用时再重新创建并添加到html中。代码如下:/** *按钮事件实现函数 *原理:利用input标签的file类别,打开选择文件对话框 *通过change事件,将选择的文件返回。为了使每次选择的文件都得到更新, *在input对象用完后每次都移除出html中,下次使用时再重新创建并添加到html中 */ btnClickFun:function(dir){ // 创建input标签 var inputObj=document.createElement('input') // 设置属性 inputObj.setAttribute('id','_ef'); inputObj.setAttribute('type','file'); inputObj.setAttribute("style",'visibility:hidden'); if(dir){ // 如果要选择路径,则添加以下两个属性 inputObj.setAttribute('webkitdirectory', ""); inputObj.setAttribute('directory', ""); } // 添加到DOM中 document.body.appendChild(inputObj); // 添加事件监听器 inputObj.addEventListener("change",this.updatePath); // 模拟点击 inputObj.click(); }, // 打开文件选择器input标签的change事件响应 updatePath:function(){ var inputObj = document.getElementById("_ef"); var files = inputObj.files; console.log(files) try{ if(files.length > 1){ alert('当前仅支持选择一个文件') } else{ switch(this.btntype){ case 'store': // 临时变量的值赋给输出路径 this.outpath = files[0].path; break; case 'add': // 添加文件操作 this.filepath = files[0].path; if(this.addFile(this.filepath)){ alert("添加成功") } break; default: break; } } // 移除事件监听器 inputObj.removeEventListener("change",function(){}); // 从DOM中移除input document.body.removeChild(inputObj); }catch (error) { alert(error) } },btnClickFun函数中创建并设置了input标签属性及监听器,函数updatePath为change事件监听的回调函数。通过input标签对象的files属性获得选中的文件名。2.第二种方法,electron首先在子进程中引入ipcRenderer模块,import {ipcRenderer} from 'electron'利用该模块向主进程发送“open-directory-dialog”消息,配置参数为“openDirectory”或“openFile”,并且设置主进程返回的消息“selectedItem”的回调函数为getPath,// 按钮点击事件 btnClick:function(type){ this.btntype = type; // 判断点击事件是哪个按钮发出的 switch(type){ case 'store': // 选择存贮路径 //this.btnClickFun(true); ipcRenderer.send('open-directory-dialog','openDirectory'); ipcRenderer.on('selectedItem',this.getPath); break; case 'add': // 添加文件 //this.btnClickFun(false); ipcRenderer.send('open-directory-dialog','openFile'); ipcRenderer.on('selectedItem',this.getPath); break; case 'remove': this.deleteItem(); break; case 'pack': break; default: break; } }, getPath:function(e,path){ console.log(path) if(path == null){ alert('请选择一个文件/文件夹') } else{ switch(this.btntype){ case 'store': // 临时变量的值赋给输出路径 this.outpath = path; break; case 'add': // 添加文件操作 this.filepath = path; if(this.addFile(this.filepath)){ alert("添加成功") } break; default: break; } } },然后在主进程中设置好子进程的消息监听,并且引入dialog模块import { dialog } from 'electron'// 绑定打开对话框事件ipcMain.on('open-directory-dialog', function (event,p) { dialog.showOpenDialog({ properties: [p] },function (files) { if (files){// 如果有选中 // 发送选择的对象给子进程 event.sender.send('selectedItem', files[0]) } })});这样就可以完成选择文件/文件夹的操作了。3.第一种方法实现的vue组件纯JS实现的文件选择器,需要操作DOM原理:利用input标签的file类别,打开选择文件对话框通过change事件,将选择的文件返回。为了使每次选择的文件都得到更新,在input对象用完后每次都移除出html中,下次使用时再重新创建并添加到html中默认打开文件夹,如果需要选择文件,则需要在调用处配置属性dir='file'属性caption显示按钮的文本信息成功调用后会向父进程发送一个‘btnSelectItem’消息用于返回选中的文件全路径 ...