webkitdirectory property/ directory upload form/ react typescript

371 Views Asked by At

Webkitdirectory is a HTML attribute and indicates that the input element should let the user select directories instead of files. When a directory is selected, the directory and its entire hierarchy of contents are included in the set of selected items.

But there is a problem with how webkitdirectory actually works. If I have the following directory structure:

folderA:

  • image.png
  • folderB

using webkitdirectory won't give me any data on folderB, as it is empty. This can be easily checked on their page.

I am creating a cloud storage type web app in react and I'd like to respect the directory structure the user has when uploading a directory. In my project you can create empty directories but this should be a bonus function not the solution to not being able to upload empty directories.

This question has popped a few times around here but the answers didn't seem to actually understand the problem.

export const App = () => {
  type WebkitDirectoryInputProps = React.HTMLProps<HTMLInputElement> & {
    webkitdirectory?: string;
  };

  const WebkitDirectoryInput: React.FC<WebkitDirectoryInputProps> = (props) => {
    return <input {...props} />;
  };
  const [selectedFolder, setSelectedFolder] = useState<FileList | null>(null);

  const handleFolderChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedFolder((prev) => (event.target?.files ? event.target?.files : prev));
  };
  const handleFolder = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (selectedFolder) {
      for (let i = 0; i < selectedFolder.length; i++) {
        console.log(selectedFolder[i].webkitRelativePath);
      }
    }
    setSelectedFolder(null);
    event.currentTarget.reset();
  };
  return (
    <form onSubmit={handleFolder}>
        <WebkitDirectoryInput type="file" webkitdirectory="true" onChange={handleFolderChange} />
        <Button type="submit">Send</Button>
     </form>
0

There are 0 best solutions below