Electron opens the file and obtains the absolute path

Electron opens the file and obtains the absolute path

In desktop applications, it is common to click a button, select a file, and get the absolute path in the background for subsequent processing.

If you use the Input tag File to import, the following example:

<!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>

Due to security policy reasons, what is obtained is an incomplete path "fakepath", the absolute path cannot be obtained directly, and other methods are required.
Insert picture description here
How Electron obtains the absolute path from the opened file:

  1. Introduce Jquery settings
 <script>
 window.$ = window.jQuery = require('./js/jquery-3.3.1.min.js');
 </script>
  1. Design hidden File type Input tags
 <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. Design a button that triggers to open a file
 <div> 
<button type="button" id="open_file">Open File</button>
</div>
  1. Design control script
<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>

Among them, tn is used to deal with the possibility of multiple false triggers.
Insert picture description here
Reference design download link:
https://download.csdn.net/download/hwytree/12524049

-End-

Guess you like

Origin blog.csdn.net/hwytree/article/details/106759424