Folder upload using webkitdirectory and directory not Working on safari browser

2.1k views Asked by At

I am trying to upload directory using input type file.Its Working fine in GoogleChrome and FireFox but while I am testing it in Safari browser its not working its allowing user to select single file as well. Is there any way to restrict user to select single file and allowed only to select folder in Safari browser.

here is my code where I am using:

const UploadFolder = props => {
  return (
<span>
<a className="dropdown-item" href='#'>
  <i className="fa fa-cloud-upload mr-2 upload-icon" aria-hidden="true"></i>Upload Files Folder</a>
 <input type='file' onChange={(e) => { props.onFolderSelect(e) }} 
 directory="" webkitdirectory="" mozdirectory="" allowdirs="" multiple />
</span>
)
}

export default UploadFolder;

If anyone knows the solution for Safari browser please guide me.

any help will be appreciated.

Thanks in Advance,

2

There are 2 answers

0
NCTH On

Hi i found a some way to make safari can only select a folder but maybe it's a little bit tricky by using accept extension to block all file extension in safari

In macOS maximum file extension length is limit at 255 character so i'll generate random extension which length more than 255 character and pass it into webkitDirectory input type file

// Example
const fakeExtension = `.${a.repeat(256)},`;
const isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));
return (
  <input
    type="file"
    id="folder-uploader"
    accept={isSafari ? fakeExtension : ''}
    webkitdirectory=""
  />
);
0
Nick Wong On

I think it is not necessary to fake a 256 length extension string. Any extension that no file can match will work as well. I tweaked a little bit to NCTH's answer.

const fakeExtension = `..`; // no file will match this;

return (
  <input
    type="file"
    accept={fakeExtension}
    webkitdirectory=""
  />
);