admin管理员组

文章数量:1295267

I'm trying to build a React + Electron app that supports file drag and drop. The goal is for users to be able to drag files into a box, and for the app to retrieve the full file path from the user's system. Right now, I'm able to capture and display the file names, but the path always ends up being null or an empty string.

Here’s the GitHub repo (main branch) with my code:

When I drag a file, I can see something like this in my main.js logs: 1 File dropped: 11-shonuff_by_omid-cms.mp3 - undefined

Below are the relevant parts of my code. (Note: I'm including the import statements as well.)

import React, { useState } from 'react';
import './App.css';

function App() {
  const [files, setFiles] = useState([]);

  const handleDrop = (event) => {
    event.preventDefault();
    const droppedFiles = Array.from(event.dataTransfer.files);
    setFiles(droppedFiles);
    droppedFiles.forEach(file => {
      console.log(`File dropped: ${file.name} - ${file.path}`);
    });
    if (window.electron) {
      console.log('Sending files-dropped event to main process');
      window.electron.sendFiles(droppedFiles.map(file => ({ name: file.name, path: file.path })));
    }
  };

  const handleFileSelect = (event) => {
    const selectedFiles = Array.from(event.target.files);
    setFiles(selectedFiles);
    selectedFiles.forEach(file => {
      console.log(`File selected: ${file.name} - ${file.path}`);
    });
    if (window.electron) {
      console.log('Sending files-dropped event to main process');
      window.electron.sendFiles(selectedFiles.map(file => ({ name: file.name, path: file.path })));
    }
  };

  const handleDragOver = (event) => {
    event.preventDefault();
  };

  return (
    <div className="App">
      <div
        className="drop-zone"
        onDrop={handleDrop}
        onDragOver={handleDragOver}
      >
        <p>Drag and drop files here, or click to select files</p>
        <input type="file" multiple onChange={handleFileSelect} />
      </div>
      <ul>
        {files.map((file, index) => (
          <li key={index}>{file.name} - {file.path}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')  // Add this line
    },
  });

  const isDev = !app.isPackaged; // Check if the app is in development mode
  const startUrl = isDev
    ? 'http://localhost:3000' // Load from React dev server
    : `file://${path.join(__dirname, 'build', 'index.html')}`;

  mainWindow.loadURL(startUrl);

  if (isDev) {
    mainWindow.webContents.openDevTools(); // Open DevTools in development mode
  }

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

ipcMain.on('files-dropped', (event, files) => {
  console.log('Received files-dropped event');
  files.forEach(file => {
    console.log(`File dropped: ${file.name} - ${file.path}`);
  });
});

app.whenReady().then(() => {
  console.log('App is ready');
  createWindow();
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (mainWindow === null) createWindow();
});

What I've tried / Additional Info:

  • I've confirmed that I'm able to retrieve the file name from file.name.
  • However, file.path is always coming up undefined in both the renderer and the main process logs.
  • I tried enabling nodeIntegration, but I understand that's not ideal for security reasons. Also, that didn't fix the path issue.

Question: How do I properly retrieve the full file path for each dropped file in a React + Electron setup? Is there something in my current setup preventing the path from being captured? Any tips or recommended changes to my preload scripts or webPreferences in BrowserWindow?

Thank you in advance for any guidance!

I'm trying to build a React + Electron app that supports file drag and drop. The goal is for users to be able to drag files into a box, and for the app to retrieve the full file path from the user's system. Right now, I'm able to capture and display the file names, but the path always ends up being null or an empty string.

Here’s the GitHub repo (main branch) with my code: https://github/MartinBarker/electron-react-file-drop

When I drag a file, I can see something like this in my main.js logs: 1 File dropped: 11-shonuff_by_omid-cms.mp3 - undefined

Below are the relevant parts of my code. (Note: I'm including the import statements as well.)

import React, { useState } from 'react';
import './App.css';

function App() {
  const [files, setFiles] = useState([]);

  const handleDrop = (event) => {
    event.preventDefault();
    const droppedFiles = Array.from(event.dataTransfer.files);
    setFiles(droppedFiles);
    droppedFiles.forEach(file => {
      console.log(`File dropped: ${file.name} - ${file.path}`);
    });
    if (window.electron) {
      console.log('Sending files-dropped event to main process');
      window.electron.sendFiles(droppedFiles.map(file => ({ name: file.name, path: file.path })));
    }
  };

  const handleFileSelect = (event) => {
    const selectedFiles = Array.from(event.target.files);
    setFiles(selectedFiles);
    selectedFiles.forEach(file => {
      console.log(`File selected: ${file.name} - ${file.path}`);
    });
    if (window.electron) {
      console.log('Sending files-dropped event to main process');
      window.electron.sendFiles(selectedFiles.map(file => ({ name: file.name, path: file.path })));
    }
  };

  const handleDragOver = (event) => {
    event.preventDefault();
  };

  return (
    <div className="App">
      <div
        className="drop-zone"
        onDrop={handleDrop}
        onDragOver={handleDragOver}
      >
        <p>Drag and drop files here, or click to select files</p>
        <input type="file" multiple onChange={handleFileSelect} />
      </div>
      <ul>
        {files.map((file, index) => (
          <li key={index}>{file.name} - {file.path}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')  // Add this line
    },
  });

  const isDev = !app.isPackaged; // Check if the app is in development mode
  const startUrl = isDev
    ? 'http://localhost:3000' // Load from React dev server
    : `file://${path.join(__dirname, 'build', 'index.html')}`;

  mainWindow.loadURL(startUrl);

  if (isDev) {
    mainWindow.webContents.openDevTools(); // Open DevTools in development mode
  }

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

ipcMain.on('files-dropped', (event, files) => {
  console.log('Received files-dropped event');
  files.forEach(file => {
    console.log(`File dropped: ${file.name} - ${file.path}`);
  });
});

app.whenReady().then(() => {
  console.log('App is ready');
  createWindow();
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (mainWindow === null) createWindow();
});

What I've tried / Additional Info:

  • I've confirmed that I'm able to retrieve the file name from file.name.
  • However, file.path is always coming up undefined in both the renderer and the main process logs.
  • I tried enabling nodeIntegration, but I understand that's not ideal for security reasons. Also, that didn't fix the path issue.

Question: How do I properly retrieve the full file path for each dropped file in a React + Electron setup? Is there something in my current setup preventing the path from being captured? Any tips or recommended changes to my preload scripts or webPreferences in BrowserWindow?

Thank you in advance for any guidance!

Share Improve this question edited Feb 13 at 12:43 DarkBee 15.6k8 gold badges72 silver badges116 bronze badges asked Feb 12 at 7:23 MartinMartin 1,5824 gold badges41 silver badges90 bronze badges 2
  • Have you tried webUtils.getPathForFile(file)? – Lã Ngọc Hải Commented Feb 12 at 7:49
  • @LãNgọcHải if i try including the line import { webUtils } from 'electron'; I get an error saying SyntaxError: The requested module 'electron' does not provide an export named 'webUtils' – Martin Commented Feb 16 at 2:50
Add a comment  | 

1 Answer 1

Reset to default 1

The path property that Electron adds to the File interface was removed in Electron 32: https://github/electron/electron/pull/42053.

Electron recommends using webUtils.getPathForFile (https://www.electronjs./docs/latest/api/file-object/) instead.

Your code should look something like this:

const {webUtils} = require('electron')
const filePath = webUtils.getPathForFile(fileObject)

本文标签: javascriptHow to get filepath after dropping fileStack Overflow