user856232
user856232

Reputation: 1113

Browser Folder Uploading

I would like to be able to have a user upload a folder with all the files and folders inside it and retain the hierarchy to my web app using just the browser.

I have searched and not found how to do this. Everyone says that it is a browser problem and I believe it because there is not browser standard for doing this.

I have found and played with many javascript implementations of uploading files. When I drag a folder onto them I can get the list of all the files, but the folders and hierarchy are all gone. If I use the ones that open a dialog to find a file none of them allow selecting a folder.

So how does Dropbox do it?

I can drag a whole folder onto either Chrome or Safari (on my mac) and both of them will upload the folders and files and retain the hierarchy in dropbox.

Doesn't anyone know how they do that so that I can do the same on my own web app that is browser based?

Upvotes: 7

Views: 14729

Answers (2)

Shahed
Shahed

Reputation: 1885

To upload folders from browser, you need to set a few attributes,

Chrome,firefox doesn't allow to select file/folder in the same go, to do this you need set a few attributes.

  1. InputEl.setAttribute("directory",directory")
  2. InputEl.setAttribute("webkitdirectory","webkitdirectory")

To retain the folder structure. You need to use webkitrelativepath

 <input
      type="file"
      directory="directory"
      multiple
      webkitdirectory="webkitdirectory"
      id="files"
    />
document.getElementById("files").addEventListener("input", (e) => {
  console.log(document.getElementById("files").files);//fileList
});

Convert fileList(readonly) to an Array and loop over them and store the webkitRelativePathvalue and update them to your backend, that is a way to retain the dir structure have been uploaded.

NOTE: while uploading a file,webkitRelativePath will be "" and for only when directory and webKitRelativePath attributes are present you are allowed to upload a folder and for these files only you will have webkitRelativePath with some value.

Upvotes: 2

caylee
caylee

Reputation: 941

You have to add some parameters to the input tag to support directory uploads: webkitdirectory for Webkit-based browsers (e.g., Chrome) and mozdirectory for Mozilla's browser (Firefox).

The HTML code could look like this:

<input type="file" webkitdirectory mozdirectory … />

You could have a look at https://stackoverflow.com/a/46562869 and https://stackoverflow.com/a/8218074, which are answers to similar questions.

Upvotes: 6

Related Questions