Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron: get full path of uploaded file

Tags:

I'm buildind now GUI using Electron. (like PhoneGap for desktop apps)

Is there a way to enable full path for file checked in <input type="file">?
Insted of C:\fakepath\dataset.zip now. (the directory name isn't "fakepath", but that is the value of document.getElementById("myFile").value)

Or, is there other way to select a file?

like image 270
Dani-Br Avatar asked Jul 22 '16 15:07

Dani-Br


2 Answers

Electron adds a path property to File objects, so you can get the real path from the input element using:

document.getElementById("myFile").files[0].path
like image 71
Vadim Macagon Avatar answered Sep 23 '22 21:09

Vadim Macagon


It is not possible to do what you are trying for security reasons, according this answer How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?.

However you could do a work around like I did in an electron project I worked on.

  1. Create a HTML button
  2. Then in the renderer process create an event listener to the button you created before.

    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. Then in the main process you use the showOpenDialog to choose a file and then send the full path back to the renderer process.

    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. Then in the renderer process you get the full path.

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

Thus you can have a similar behaviour than the input type file and get the full path.

like image 32
Piero Divasto Avatar answered Sep 22 '22 21:09

Piero Divasto