2016-07-22 171 views
2

我現在使用Electron構建了一個GUI。 (如PhoneGap的桌面應用程序)Electron:獲取上傳文件的完整路徑

有沒有辦法啓用文件檢查的完整路徑<input type="file">
立即拒絕C:\fakepath\dataset.zip。 (目錄名稱不是「fakepath」,但值是document.getElementById("myFile").value

或者,還有其他方法可以選擇文件嗎?

+2

'C:\ fakepath \ dataset.zip'是一個完整的路徑。你什麼意思? –

+0

不,目錄名稱不是'fakepath',但這正是我從document.getElementById(「myFile」).value獲得的。 –

+0

你不能得到像這樣的輸入文件。 –

回答

7

電子增添了path屬性File對象,這樣你就可以使用您可以通過輸入元的真實路徑:

document.getElementById("myFile").files[0].path 
1

根據這個回答How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?,你不可能爲了安全原因去做你正在嘗試的東西。

但是,您可以像我在我所從事的電子項目中那樣做一項工作。

  1. 創建HTML按鈕
  2. 然後在渲染過程創建一個事件偵聽到您之前創建的按鈕。

    const ipc = require('electron').ipcRenderer; 
    const buttonCreated = document.getElementById('button-created-id'); 
    
    buttonCreated.addEventListener('click', function (event) { 
        ipc.send('open-file-dialog-for-file') 
    }); 
    
  3. 然後在主要工藝使用showOpenDialog選擇一個文件,然後發送full path回到渲染過程。

    ipc.on('open-file-dialog-for-file', function (event) { 
    if(os.platform() === 'linux' || os.platform() === 'win32'){ 
        dialog.showOpenDialog({ 
         properties: ['openFile'] 
        }, function (files) { 
         if (files) event.sender.send('selected-file', files[0]); 
        }); 
    } else { 
        dialog.showOpenDialog({ 
         properties: ['openFile', 'openDirectory'] 
        }, function (files) { 
         if (files) event.sender.send('selected-file', files[0]); 
        }); 
    }}); 
    
  4. 然後在渲染過程你得到的full path

    ipc.on('selected-file', function (event, path) { 
        console.log('Full path: ', path); 
    }); 
    

因此,你可以擁有比輸入類型的文件類似的行爲,並得到完整路徑。

+0

*「出於安全原因不可能做你正在嘗試的事情」* - 對於最終用戶瀏覽器而言,這是真的,但對於Electron來說則是如此。我相信你可以簡單地使用'input.files [0] .path',這在[當前接受的答案](http://stackoverflow.com/a/38549837/2788872)中也有描述。 –

-1
<script>const electron = require('electron');</script> 
<button id="myFile" onclick="this.value=electron.remote.dialog.showOpenDialog()[0]">UpdateFile</button> 

現在,document.getElementById("myFile").value將包含所選文件的完整路徑。

相關問題