如何从资源管理器中删除文件并获取其到 electrojs 应用程序的完整路径

pok*_*mon 6 electron electron-forge

我正在使用带有打字稿集成的电子锻造。

我找不到从资源管理器拖放文件并获取其完整路径的解决方案

我在index.ts中添加了以下内容:

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

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

但当我拖放文件时不显示任何内容

有任何想法吗?

cac*_*que 6

首先你需要掌握一些概念:

操作发生在renderer使用 获取删除的文件HTML5 FIle API并将文件路径传递给mainusing上electron's IPC

渲染器.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);
});
Run Code Online (Sandbox Code Playgroud)

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
})
Run Code Online (Sandbox Code Playgroud)

  • 感谢您非常干净且有效的解决方案! (2认同)