跳转到主要内容

选项参考

useDropup hook 的所有配置选项。

验证选项

accept

接受的文件类型。

// 单个 MIME 类型
useDropup({ accept: 'image/png' });

// 多个 MIME 类型
useDropup({ accept: 'image/png, image/jpeg, image/gif' });

// 通配符
useDropup({ accept: 'image/*' });

// 按扩展名
useDropup({ accept: '.pdf, .doc, .docx' });

// 数组格式
useDropup({ accept: ['image/*', 'application/pdf', '.txt'] });
类型默认值
string | string[]undefined (所有文件)

maxSize

最大文件大小(字节)。

useDropup({ maxSize: 10 * 1024 * 1024 }); // 10MB
类型默认值
numberundefined (无限制)

minSize

最小文件大小(字节)。

useDropup({ minSize: 1024 }); // 最小 1KB
类型默认值
numberundefined (无限制)

maxFiles

允许的最大文件数量。

useDropup({ maxFiles: 5 });
类型默认值
numberundefined (无限制)

maxWidth / maxHeight

最大图片尺寸(像素)。

useDropup({
accept: 'image/*',
maxWidth: 4096,
maxHeight: 4096,
});
类型默认值
numberundefined (无限制)

minWidth / minHeight

最小图片尺寸(像素)。

useDropup({
accept: 'image/*',
minWidth: 100,
minHeight: 100,
});
类型默认值
numberundefined (无限制)

customRules

自定义验证函数。

useDropup({
customRules: [
// 同步验证
(file) => {
if (file.name.includes('draft')) {
return '不允许草稿文件';
}
return true;
},
// 异步验证
async (file) => {
const exists = await checkServerDuplicate(file);
return exists ? '文件已存在' : true;
},
],
});
类型默认值
ValidationRule[][]

ValidationRule 类型:

type ValidationRule = (file: File) => boolean | string | Promise<boolean | string>;

行为选项

multiple

允许选择多个文件。

useDropup({ multiple: true });  // 多个文件
useDropup({ multiple: false }); // 仅单个文件
类型默认值
booleantrue

disabled

禁用拖放区域。

useDropup({ disabled: true });
类型默认值
booleanfalse

autoUpload

添加文件时自动开始上传。

useDropup({
upload: { url: '/api/upload' },
autoUpload: true,
});
类型默认值
booleanfalse

generatePreviews

为图片文件生成预览 URL。

useDropup({ generatePreviews: true });

// 访问预览
files[0].preview // "blob:http://..."
类型默认值
booleantrue

上传配置

upload

配置上传目标和行为。

基于 URL 的配置

useDropup({
upload: {
url: '/api/upload',
method: 'POST',
headers: {
'Authorization': 'Bearer token',
},
fieldName: 'file',
withCredentials: true,
timeout: 30000,
},
});

UploadConfig 属性:

属性类型默认值描述
urlstring必需上传端点 URL
methodstring'POST'HTTP 方法
headersRecord<string, string>{}请求头
fieldNamestring'file'文件的表单字段名
withCredentialsbooleanfalse包含 cookies
timeoutnumber0请求超时时间(毫秒)
dataRecord<string, unknown>{}额外的表单数据

自定义上传器

useDropup({
upload: async (file, options) => {
const formData = new FormData();
formData.append('file', file.file);

const response = await fetch('/api/upload', {
method: 'POST',
body: formData,
signal: options.signal,
});

const data = await response.json();
return { url: data.url };
},
});

CustomUploader 类型:

type CustomUploader = (
file: DropupFile,
options: UploadOptions
) => Promise<UploadResult>;

interface UploadOptions {
signal: AbortSignal;
onProgress: (progress: number) => void;
}

interface UploadResult {
url?: string;
response?: unknown;
}

云上传器

import { createS3Uploader } from '@samithahansaka/dropup/cloud/s3';

useDropup({
upload: createS3Uploader({
getPresignedUrl: async (file) => {
const res = await fetch('/api/s3-presign', {
method: 'POST',
body: JSON.stringify({ filename: file.name, type: file.type }),
});
return res.json();
},
}),
});

回调选项

onFilesAdded

当文件添加时调用(验证后)。

useDropup({
onFilesAdded: (files) => {
console.log('已添加:', files.map(f => f.name));
},
});
类型
(files: DropupFile[]) => void

onFileRemoved

当文件被移除时调用。

useDropup({
onFileRemoved: (file) => {
console.log('已移除:', file.name);
},
});
类型
(file: DropupFile) => void

onValidationError

当文件验证失败时调用。

useDropup({
accept: 'image/*',
onValidationError: (errors) => {
errors.forEach(({ file, errors }) => {
console.log(`${file.name}: ${errors.join(', ')}`);
});
},
});
类型
(errors: ValidationError[]) => void

onUploadStart

当文件开始上传时调用。

useDropup({
onUploadStart: (file) => {
console.log('开始上传:', file.name);
},
});
类型
(file: DropupFile) => void

onUploadProgress

在上传进度更新时调用。

useDropup({
onUploadProgress: (file, progress) => {
console.log(`${file.name}: ${progress}%`);
},
});
类型
(file: DropupFile, progress: number) => void

onUploadComplete

当文件上传完成时调用。

useDropup({
onUploadComplete: (file, response) => {
console.log('已上传:', file.uploadedUrl);
console.log('服务器响应:', response);
},
});
类型
(file: DropupFile, response: unknown) => void

onUploadError

当文件上传失败时调用。

useDropup({
onUploadError: (file, error) => {
console.error(`失败: ${file.name}`, error.message);
},
});
类型
(file: DropupFile, error: DropupError) => void

onAllComplete

当所有文件上传完成时调用。

useDropup({
onAllComplete: (files) => {
const successful = files.filter(f => f.status === 'complete');
console.log(`${successful.length}/${files.length} 上传成功`);
},
});
类型
(files: DropupFile[]) => void

完整示例

const { files, actions, state, getDropProps, getInputProps } = useDropup({
// 验证
accept: ['image/*', 'application/pdf'],
maxSize: 10 * 1024 * 1024,
maxFiles: 5,

// 行为
multiple: true,
autoUpload: false,
generatePreviews: true,

// 上传
upload: {
url: '/api/upload',
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
},
},

// 回调函数
onFilesAdded: (files) => {
toast.info(`已添加 ${files.length} 个文件`);
},
onValidationError: (errors) => {
toast.error(`${errors.length} 个文件被拒绝`);
},
onUploadProgress: (file, progress) => {
console.log(`${file.name}: ${progress}%`);
},
onUploadComplete: (file) => {
toast.success(`${file.name} 上传成功!`);
},
onUploadError: (file, error) => {
toast.error(`${file.name} 失败: ${error.message}`);
},
onAllComplete: (files) => {
const count = files.filter(f => f.status === 'complete').length;
toast.success(`全部完成! ${count} 个文件已上传。`);
},
});