useDropup Hook
支持拖放上传的主要文件上传 hook。
导入
import { useDropup } from '@samithahansaka/dropup';
基本用法
const {
files,
state,
actions,
getDropProps,
getInputProps,
openFileDialog,
} = useDropup(options);
参数
options (可选)
完整详情请参见 选项。
interface UseDropupOptions {
// 验证
accept?: string | string[];
maxSize?: number;
minSize?: number;
maxFiles?: number;
maxWidth?: number;
maxHeight?: number;
minWidth?: number;
minHeight?: number;
customRules?: ValidationRule[];
// 行为
multiple?: boolean;
disabled?: boolean;
autoUpload?: boolean;
generatePreviews?: boolean;
// 上传配置
upload?: UploadConfig | CustomUploader;
// 回调函数
onFilesAdded?: (files: DropupFile[]) => void;
onFileRemoved?: (file: DropupFile) => void;
onValidationError?: (errors: ValidationError[]) => void;
onUploadStart?: (file: DropupFile) => void;
onUploadProgress?: (file: DropupFile, progress: number) => void;
onUploadComplete?: (file: DropupFile, response: unknown) => void;
onUploadError?: (file: DropupFile, error: DropupError) => void;
onAllComplete?: (files: DropupFile[]) => void;
}
返回值
完整详情请参见 返回值。
interface UseDropupReturn {
// 状态
files: DropupFile[];
state: DropupState;
// 操作
actions: DropupActions;
// Prop getter 函数
getDropProps: <E extends HTMLElement>(props?: HTMLAttributes<E>) => DropZoneProps<E>;
getInputProps: (props?: InputHTMLAttributes) => InputProps;
// 工具函数
openFileDialog: () => void;
}
快速参考
Files 数组
const { files } = useDropup();
// 每个文件包含:
files[0].id // 唯一 ID
files[0].file // 原始 File 对象
files[0].name // 文件名
files[0].size // 字节大小
files[0].type // MIME 类型
files[0].preview // 预览 URL (图片)
files[0].status // 'idle' | 'uploading' | 'complete' | 'error'
files[0].progress // 0-100
files[0].uploadedUrl // 上传后的 URL
files[0].error // 如果失败则包含错误信息
State 对象
const { state } = useDropup();
state.isDragging // 文件正在拖放区域上方
state.isDragAccept // 拖放的文件有效
state.isDragReject // 拖放的文件无效
state.isUploading // 任何文件正在上传
state.progress // 总体进度 0-100
state.status // 'idle' | 'uploading' | 'complete' | 'error'
Actions 对象
const { actions } = useDropup();
actions.upload(fileIds?) // 开始上传
actions.cancel(fileId?) // 取消上传
actions.remove(fileId) // 移除文件
actions.reset() // 清除所有
actions.retry(fileIds?) // 重试失败的文件
actions.addFiles(files) // 以编程方式添加文件
actions.updateFileMeta(id, meta) // 更新元数据
Prop Getters
const { getDropProps, getInputProps } = useDropup();
// 应用到拖放区域
<div {...getDropProps()}>
<input {...getInputProps()} />
拖放到这里
</div>
// 使用自定义 props
<div {...getDropProps({ className: 'my-dropzone', onClick: handleClick })}>
...
</div>
示例
最小示例
function Uploader() {
const { files, getDropProps, getInputProps } = useDropup();
return (
<div {...getDropProps()}>
<input {...getInputProps()} />
<p>将文件拖放到这里</p>
<ul>
{files.map(f => <li key={f.id}>{f.name}</li>)}
</ul>
</div>
);
}
带上传功能
function Uploader() {
const { files, actions, getDropProps, getInputProps } = useDropup({
upload: {
url: '/api/upload',
method: 'POST',
headers: { 'Authorization': 'Bearer token' },
},
});
return (
<div>
<div {...getDropProps()}>
<input {...getInputProps()} />
<p>将文件拖放到这里</p>
</div>
{files.map(f => (
<div key={f.id}>
{f.name} - {f.status}
{f.status === 'uploading' && ` ${f.progress}%`}
</div>
))}
<button onClick={() => actions.upload()}>全部上传</button>
</div>
);
}
完整功能示例
function FullFeaturedUploader() {
const {
files,
state,
actions,
getDropProps,
getInputProps,
} = useDropup({
// 验证
accept: 'image/*',
maxSize: 10 * 1024 * 1024,
maxFiles: 5,
// 行为
multiple: true,
autoUpload: true,
generatePreviews: true,
// 上传
upload: {
url: '/api/upload',
method: 'POST',
},
// 回调函数
onFilesAdded: (files) => console.log('已添加:', files),
onUploadComplete: (file) => console.log('完成:', file.uploadedUrl),
onUploadError: (file, err) => console.error('错误:', err),
onAllComplete: () => console.log('所有上传完成!'),
});
return (
<div>
<div
{...getDropProps()}
style={{
border: `2px dashed ${state.isDragAccept ? 'green' : state.isDragReject ? 'red' : 'gray'}`,
padding: 40,
}}
>
<input {...getInputProps()} />
<p>将图片拖放到这里 (最多 5 个,每个最大 10MB)</p>
</div>
{files.map(file => (
<div key={file.id}>
{file.preview && <img src={file.preview} width={50} />}
<span>{file.name}</span>
<span>{file.status}</span>
{file.status === 'uploading' && <span>{file.progress}%</span>}
<button onClick={() => actions.remove(file.id)}>×</button>
</div>
))}
{state.isUploading && <p>上传中... {state.progress}%</p>}
</div>
);
}