This commit is contained in:
@@ -12,6 +12,34 @@ type Props = {
|
||||
accept?: string;
|
||||
}
|
||||
|
||||
const MIME_TO_EXTENSIONS: Record<string, string[]> = {
|
||||
'image/png': ['.png'],
|
||||
'image/svg+xml': ['.svg'],
|
||||
'image/jpeg': ['.jpg', '.jpeg'],
|
||||
'image/gif': ['.gif'],
|
||||
'image/webp': ['.webp'],
|
||||
}
|
||||
|
||||
const buildAcceptTypes = (accept?: string) => {
|
||||
if (!accept) return undefined
|
||||
|
||||
return accept.split(',').reduce<Record<string, string[]>>((acc, type) => {
|
||||
const trimmed = type.trim()
|
||||
if (trimmed.startsWith('.')) {
|
||||
const ext = trimmed.toLowerCase()
|
||||
const mimeEntry = Object.entries(MIME_TO_EXTENSIONS).find(([, exts]) => exts.includes(ext))
|
||||
if (mimeEntry) {
|
||||
acc[mimeEntry[0]] = mimeEntry[1]
|
||||
}
|
||||
} else if (MIME_TO_EXTENSIONS[trimmed]) {
|
||||
acc[trimmed] = MIME_TO_EXTENSIONS[trimmed]
|
||||
} else {
|
||||
acc[trimmed] = []
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
}
|
||||
|
||||
const UploadBox: FC<Props> = (props: Props) => {
|
||||
|
||||
const { t } = useTranslation('global')
|
||||
@@ -19,8 +47,7 @@ const UploadBox: FC<Props> = (props: Props) => {
|
||||
|
||||
const onDrop = useCallback((acceptedFiles: File[]) => {
|
||||
if (props.isMultiple) {
|
||||
const array = [...files]
|
||||
array.push(acceptedFiles[0])
|
||||
const array = [...files, ...acceptedFiles]
|
||||
setFiles(array)
|
||||
if (props.onChange) {
|
||||
props.onChange(array);
|
||||
@@ -33,9 +60,11 @@ const UploadBox: FC<Props> = (props: Props) => {
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [files])
|
||||
const acceptTypes = buildAcceptTypes(props.accept)
|
||||
const { getRootProps, getInputProps } = useDropzone({
|
||||
onDrop,
|
||||
accept: props.accept ? { [props.accept]: [] } : undefined
|
||||
accept: acceptTypes,
|
||||
multiple: props.isMultiple,
|
||||
})
|
||||
|
||||
const handleRemove = (index: number) => {
|
||||
|
||||
Reference in New Issue
Block a user