electronelectron-forge

How to drop a file from explorer and get it's full path to electronjs app


I am using electron forge with typescript integration.

I can't find a solution to drag and drop files from explorer and get their full paths

I put in index.ts the following:

import {app, BrowserWindow, ipcMain} from 'electron';

ipcMain.on('ondragstart', (event, filepath) => {
    console.log("ondragstart " + filepath); // doesn't work
});

but doesn't show anything when I drag n drop files

any ideas?


Solution

  • First of all you need to grasp some concepts:

    Action happens on the renderer which gets the dropped files using HTML5 FIle API and passes file paths to main using electron's IPC.

    renderer.js

    document.addEventListener('dragover', (e) => {
        e.preventDefault();
        e.stopPropagation();
    });
    
    document.addEventListener('drop', (event) => {
        event.preventDefault();
        event.stopPropagation();
    
        let pathArr = [];
        for (const f of event.dataTransfer.files) {
            // Using the path attribute to get absolute file path
            console.log('File Path of dragged files: ', f.path)
            pathArr.push(f.path); // assemble array for main.js
        }
        console.log(pathArr);
        const ret = ipcRenderer.sendSync('dropped-file', pathArr);
        console.log(ret);
    });
    

    main.js

    let winmain;
    
    function createWindow () {
        winMain = new BrowserWindow({
            width: 1280,
            height: 720,
            webPreferences: {
                contextIsolation: false,
                nodeIntegration: true
            }
        })
        winMain.loadFile('index.html');
    }
    
    
    
    ipcMain.on('dropped-file', (event, arg) => {
        console.log('Dropped File(s):', arg);
        event.returnValue = `Received ${arg.length} paths.`; // Synchronous reply
    })