import React, { useEffect, useState } from "react"; import { Redirect } from "react-router-dom"; import { DefaultTemplate } from "payload/components/templates"; import { Button, Eyebrow, Gutter } from "payload/components/elements"; import { AdminView } from "payload/config"; import { useStepNav } from "payload/components/hooks"; import { useConfig, Meta } from "payload/components/utilities"; import Dropzone from "react-dropzone"; type Status = "IDLE" | "UPLOADING" | "DONE"; const BatchUploader: AdminView = ({ user, canAccessAdmin }) => { const { routes: { admin: adminRoute, api }, serverURL, } = useConfig(); const { setStepNav } = useStepNav(); // The effect below will only run one time and will allow us // to set the step nav to display our custom route name useEffect(() => { setStepNav([ { label: "Bulk uploader", }, ]); }, [setStepNav]); // If an unauthorized user tries to navigate straight to this page, // Boot 'em out if (!user || (user && !canAccessAdmin)) { return ; } // Dropzone const [files, setFiles] = useState([]); const [status, setStatus] = useState("IDLE"); const [statusTexts, setStatusTexts] = useState([]); const onDrop = (acceptedFiles) => { setFiles(acceptedFiles); }; const uploadFile = async (file): Promise => { const formData = new FormData(); formData.append("file", file); const response = await fetch(`${serverURL}${api}/media`, { method: "POST", body: formData, }); return `${file.path} – ${response.status} ${response.statusText}`; }; const onSubmit = () => { setStatus("UPLOADING"); const promises = files.map((file) => uploadFile(file)); Promise.all(promises) .then((values) => { setStatus("DONE"); setFiles([]); setStatusTexts(values); }) .catch((err) => console.error(`Error in Promise ${err}`)); }; return ( Media batch uploader {({ getRootProps, getInputProps }) => ( Drag'n'drop some files here, or click to select files )} {/* Dropped files list */} {files && ( {files.map((file) => ( {file.path} ))} )} {/* Status text */} {statusTexts && statusTexts.length > 0 && ( {statusTexts.map((status, i) => ( {status} ))} )} Upload ); }; export default BatchUploader;
Drag'n'drop some files here, or click to select files