Search code examples
javascriptpathelectrondrag-and-drop

How to get the absolute path of a file dragged onto an input file in Electron?


I’m developing an application using Electron and encountered an issue when trying to get the absolute path of a file that has been dragged and dropped onto a file input field.

As we know, Electron uses a browser-based interface, which makes it difficult to access the absolute paths of dragged-and-dropped files. So far, I’m able to get the absolute path of files when opening the file dialog using the dialog.showOpenDialog method in the main process, as shown in the example below:

//Process main (main.js):

// Example of how to get the absolute path of a video
ipcMain.handle('select-file', async () => {
    const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
        properties: ['openFile'],
        title: 'Select your video file',
        filters: [
            { name: 'Videos', extensions: ['mp4', 'avi', 'mov', 'mkv'] }
        ]
    });
    return canceled ? null : filePaths[0];
});
//Renderer process (renderer.js):

uploadSection.addEventListener('click', async () => {
    const filePath = await ipcRenderer.invoke('select-file');
    if (filePath) {
        console.log('Selected file:', filePath);
    }

});

This works well to open the file picker, but I would like to achieve something similar when dragging and dropping the file directly onto the input. However, since the absolute path is not directly accessible via the browser's file input API, I’m having difficulty implementing this in Electron.

Has anyone faced this or found a solution to obtain the absolute path of a file that has been dragged and dropped onto a file input in Electron?

Thanks in advance for your help!

I’ve tried several methods so far, but none seem to fit my case. I’m also wondering if web.utils.PathForFiles from Electron might be the solution, but I haven’t found any implementation examples for my case.


Solution

  • solution to get the actual path to the files on the system

    [Electron Docs] (https://www.electronjs.org/docs/latest/api/web-utils)