Electron打开文件并获得绝对路径方式

Electron打开文件并获得绝对路径方式

在桌面应用中,点击一个按钮,选择一个文件,后台再得到绝对路径进行后续处理是常见的实现。

如采用Input标签File导入的方式,如下示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Input File Path</title>
</head>
<body>
<input id="File1" type="file" />
<input type="button" value="ShowPath" onclick="alert(document.getElementById(File1).value);" />
</body>
</html>

由于安全策略原因,得到的是非完整的路径"fakepath",不能直接获得绝对路径,需采用其它方式。 Electron从打开的文件获得绝对路径的方式:

  1. 引入Jquery的设置
<script>
 window.$ = window.jQuery = require(./js/jquery-3.3.1.min.js);
 </script>
  1. 设计隐藏的File类型的Input标签
<div>
 <input type="file" class="form-control btn-block" placeholder="" readonly id="input_file" style="filter:alpha(opacity=0);opacity:0;width: 0;height: 0;">
 </div>
  1. 设计触发进行打开文件的按钮
<div> 
<button type="button" id="open_file">Open File</button>
</div>
  1. 设计控制脚本
<script>	
$("button#open_file").click(function(){OpenFile();}); 
var file_addr = "";
function OpenFile(){
	 var tn = 0;
	 $("input#input_file").change(function (){
		 if (tn == 0){
		    console.log(this.files[0]);		   
		    file_addr = this.files[0].path;   //Get file absolute path
		    console.log(file_addr);   
		     alert(`The file path is ${file_addr}`);
		                
		    this.files[0].path = "";
		 }		 
		 tn += 1;
	 });	 
	 $("input#input_file").trigger("click");
}	
	
	</script>

其中,tn用于处理多次误触发的可能。 参考设计下载地址: https://download..net/download/hwytree/12524049

-End-

经验分享 程序员 微信小程序 职场和发展