javascripthtmlreactjsnode.jselectron

How to get filepath after dropping file?


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.com/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

enter image description here

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:

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!


Solution

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

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

    Your code should look something like this:

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