I want to enable directory uploads in a react app. I tried setting webkitdirectory and mozdirectory on the input element using setAttribute
, but it didn't work.
function UploadDirectory() {
function dirUploadAttr(input) {
input.setAttribute("webkitdirectory", "");
input.setAttribute("mozdirectory", "");
}
return <input type="file" ref={dirUploadAttr} />;
}
How should I correctly enable directory uploads with react?
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