javascriptreactjstypescriptelectron

How to implement a Dropzone for folders in a React/Electron app and process the folder contents?


Is there a way in electron based apps to let a user drop a folder onto a React-component and handle the drop event so that the main process can fully access it and recursively scan the folder’s contents?

My setup so far:

const folderDropped = async (event: React.DragEvent) => {
  event.preventDefault();

  // If a folder or file has been dragged
  if (event.dataTransfer.files.length > 0) {
    const filePath = event.dataTransfer.files[0].path;
    console.log("Drop event:", event.dataTransfer.files);
    console.log("Dropped file path:", filePath);

    // Call the IPC handler: readDroppedFile
    const result = await window.api.readDroppedFile(filePath, browserWindowId);
    console.log("readDroppedFile result:", result);

     /* Further Process:
       After the api call, the object is checked if its a folder and that it contains files
       of a specific type (for example, only PNG files). Once confirmed, the main process will scan through all the
       files within the folder recursively.
    */
  }
};

Visual Studio Code, which is also built with Electron, can accept dropped files and folders from the Explorer, so it should be possible for my app as well.

Additional details (optional):


Solution

  • Ahh, I solved it now. I found the following: // Planned Breaking API Changes (32.0) >> Removed: File.path //. This can be found on the Electron website: "https://www.electronjs.org/docs/latest/breaking-changes#removed-filepath" So I have to go the way via a preload.js script.

    // (renderer)
    const file = event.dataTransfer.files[0].
    electronAPI.getFilePath(file)
    
    // (preload)
    import {
      contextBridge,
      webUtils
    } from 'electron'
    
    contextBridge.exposeInMainWorld('electronAPI', {
      getFilePath(file) {
        return webUtils.getPathForFile(file)
      }
    })