Search code examples
javascriptreactjsmernecmascript-2016

Equivalent to directory, mozdirectory and webkitdirectory in react?


I want to upload directories to my server using react and I tried using directory, mozdirectory, and webKitDirectory attributes but they didn't work and I tried to run the code that is below but unfortunately, it didn't work.

function UploadDirectory() {
  function dirUploadAttr(input) {
    input.setAttribute("webkit-directory", "");
    input.setAttribute("moz-directory", "");
  }
  return (
      <input type="file" ref={dirUploadAttr} />
  )
}

How do I take directories in the input tag in react? What is the effective and simple way to do it?


Solution

  • I'll be honest, me and a team member at the corporation I've worked at have looked into this issue for several weeks. The issue being that the users we were making our app for wanted a way to strip a file from a directory and upload it without having to double click in the directory itself to obtain the file (Ex. Click the folder containing the file in the upload menu and selecting upload to upload whole folder). Well, after digging and digging we got into contact with multiple teams in order to find a solution and they told us this: "webkitdirectory (or anything like it for that matter) is not supported in React and that's due to a Windows limitation." I believe it could have been done in the .NET era but React's specific <input)> html tag doesn't support webkitdirectory as an attribute. We instead incorporated a dropzone from the node module react-dropzone-uploader:

    import Dropzone from "react-dropzone-uploader";
    import { getDroppedOrSelectedFiles } from './Html5FileSelector'
    
      const getFilesFromEvent = (e:any) => {
        return new Promise<any>(resolve => {
          getDroppedOrSelectedFiles(e).then(chosenFiles => {
            resolve(chosenFiles.map((f:any) => f.fileObject))
          })
        })
      };
    
      const handleSubmit = (files:any) => { this.fileChange(files); }
    
      <Dropzone accept=".txt" getFilesFromEvent={getFilesFromEvent} onSubmit= 
      {handleSubmit} />
    

    Note that you will have to implement a function from Html5FileSelector, more information can be obtain from the live example showcasing the dropzone uploader, this is also a link to the official documentation of the node module: https://react-dropzone-uploader.js.org/docs/examples#!/Custom%20Input,%20Directory%20Drag%20and%20Drop