跳至主要內容

自訂驗證

為您的上傳建立精密的驗證規則。

基本自訂規則

import { useDropup } from '@samithahansaka/dropup';

function CustomValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// 規則 1:檢查檔案名稱
(file) => {
if (file.name.includes(' ')) {
return '檔案名稱不能包含空格';
}
return true;
},

// 規則 2:檢查副檔名
(file) => {
const ext = file.name.split('.').pop()?.toLowerCase();
const blocked = ['exe', 'bat', 'cmd', 'sh'];
if (ext && blocked.includes(ext)) {
return '不允許上傳可執行檔';
}
return true;
},
],

onValidationError: (errors) => {
errors.forEach(({ file, errors }) => {
alert(`${file.name}:\n${errors.join('\n')}`);
});
},
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>將檔案拖放到此處(名稱不含空格,不接受可執行檔)</p>
</div>
);
}

非同步驗證

import { useDropup } from '@samithahansaka/dropup';

function AsyncValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// 在伺服器檢查是否重複
async (file) => {
const hash = await calculateHash(file);
const response = await fetch('/api/check-duplicate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ hash, filename: file.name }),
});
const { exists } = await response.json();

if (exists) {
return '此檔案已經上傳過了';
}
return true;
},

// 驗證檔案內容
async (file) => {
if (file.type === 'application/json') {
const text = await file.text();
try {
JSON.parse(text);
return true;
} catch {
return '無效的 JSON 檔案';
}
}
return true;
},
],
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>將檔案拖放到此處(會與伺服器進行驗證)</p>
</div>
);
}

// 計算檔案雜湊的輔助函式
async function calculateHash(file: File): Promise<string> {
const buffer = await file.arrayBuffer();
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

圖片內容驗證

import { useDropup } from '@samithahansaka/dropup';

function ImageContentValidator() {
const { files, getDropProps, getInputProps } = useDropup({
accept: 'image/*',

customRules: [
// 檢查實際圖片尺寸
async (file) => {
if (!file.type.startsWith('image/')) return true;

const dimensions = await getImageDimensions(file);

if (dimensions.width < 200 || dimensions.height < 200) {
return '圖片至少需要 200x200 像素';
}

if (dimensions.width > 4000 || dimensions.height > 4000) {
return '圖片不能超過 4000x4000 像素';
}

return true;
},

// 檢查長寬比
async (file) => {
if (!file.type.startsWith('image/')) return true;

const { width, height } = await getImageDimensions(file);
const ratio = width / height;

// 要求大約正方形的圖片(比例 0.8 到 1.2)
if (ratio < 0.8 || ratio > 1.2) {
return '圖片必須大約為正方形(長寬比 0.8-1.2)';
}

return true;
},
],
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>拖放正方形圖片(最小 200px,最大 4000px)</p>

<div style={styles.gallery}>
{files.map(file => (
<img
key={file.id}
src={file.preview}
alt=""
style={styles.preview}
/>
))}
</div>
</div>
);
}

// 取得圖片尺寸的輔助函式
function getImageDimensions(file: File): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve({ width: img.width, height: img.height });
URL.revokeObjectURL(img.src);
};
img.onerror = reject;
img.src = URL.createObjectURL(file);
});
}

const styles = {
dropzone: {
border: '2px dashed #ccc',
borderRadius: 8,
padding: 40,
textAlign: 'center' as const,
},
gallery: {
display: 'flex',
gap: 8,
marginTop: 16,
justifyContent: 'center',
},
preview: {
width: 80,
height: 80,
objectFit: 'cover' as const,
borderRadius: 4,
},
};

帶相依性的驗證

import { useDropup } from '@samithahansaka/dropup';
import { useState } from 'react';

function ConditionalValidation() {
const [category, setCategory] = useState('image');

const { files, getDropProps, getInputProps } = useDropup({
// 根據類別動態設定 accept
accept: category === 'image'
? 'image/*'
: category === 'document'
? '.pdf,.doc,.docx'
: '*/*',

customRules: [
(file) => {
// 類別特定的驗證
if (category === 'image') {
if (!file.type.startsWith('image/')) {
return '請上傳圖片檔案';
}
if (file.size > 5 * 1024 * 1024) {
return '圖片必須小於 5MB';
}
}

if (category === 'document') {
if (file.size > 10 * 1024 * 1024) {
return '文件必須小於 10MB';
}
}

return true;
},
],
});

return (
<div>
<div style={{ marginBottom: 20 }}>
<label>
<input
type="radio"
value="image"
checked={category === 'image'}
onChange={() => setCategory('image')}
/>
圖片(最大 5MB)
</label>
<label style={{ marginLeft: 20 }}>
<input
type="radio"
value="document"
checked={category === 'document'}
onChange={() => setCategory('document')}
/>
文件(最大 10MB)
</label>
</div>

<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>
{category === 'image' ? '圖片' : '文件'}拖放到此處
</p>
</div>
</div>
);
}

病毒/惡意軟體掃描

import { useDropup } from '@samithahansaka/dropup';

function MalwareScanUploader() {
const { files, state, actions, getDropProps, getInputProps } = useDropup({
customRules: [
// 使用外部服務掃描檔案
async (file) => {
// 上傳到病毒掃描服務
const formData = new FormData();
formData.append('file', file);

try {
const response = await fetch('/api/scan', {
method: 'POST',
body: formData,
});

const { safe, threat } = await response.json();

if (!safe) {
return `偵測到惡意軟體: ${threat}`;
}

return true;
} catch (error) {
return '無法掃描檔案,請重試。';
}
},
],

onValidationError: (errors) => {
errors.forEach(({ file, errors }) => {
console.error(`${file.name} 被拒絕:`, errors);
});
},
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>檔案會在上傳前掃描惡意軟體</p>
</div>
);
}

預建驗證規則

import { useDropup, commonRules } from '@samithahansaka/dropup';

function PrebuiltRulesUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// 內建規則
commonRules.noExecutables, // 阻擋 .exe、.bat 等
commonRules.noHiddenFiles, // 阻擋以 . 開頭的檔案
commonRules.maxFilenameLength(50), // 最多 50 字元
commonRules.allowedExtensions(['.jpg', '.png', '.pdf']),

// 結合自訂規則
(file) => {
if (file.name.toLowerCase().includes('temp')) {
return '不允許暫存檔案';
}
return true;
},
],
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>已啟用嚴格檔案驗證</p>
</div>
);
}

驗證錯誤顯示

import { useDropup } from '@samithahansaka/dropup';
import { useState } from 'react';

type ValidationErrorType = { file: File; errors: string[] };

function ValidationErrorDisplay() {
const [validationErrors, setValidationErrors] = useState<ValidationErrorType[]>([]);

const { files, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
maxSize: 5 * 1024 * 1024,
maxFiles: 3,

customRules: [
(file) => {
if (file.name.length > 50) {
return '檔案名稱過長(最多 50 字元)';
}
return true;
},
],

onValidationError: (errors) => {
setValidationErrors(errors);

// 5 秒後清除
setTimeout(() => setValidationErrors([]), 5000);
},
});

return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>最多拖放 3 張圖片(每張最大 5MB)</p>
</div>

{/* 驗證錯誤 */}
{validationErrors.length > 0 && (
<div style={styles.errorContainer}>
<h4 style={styles.errorTitle}>部分檔案被拒絕:</h4>
{validationErrors.map(({ file, errors }, index) => (
<div key={index} style={styles.errorItem}>
<strong>{file.name}</strong>
<ul style={styles.errorList}>
{errors.map((error, i) => (
<li key={i}>{error}</li>
))}
</ul>
</div>
))}
</div>
)}

{/* 已接受的檔案 */}
{files.length > 0 && (
<div style={styles.acceptedFiles}>
<h4>已接受的檔案:</h4>
{files.map(file => (
<div key={file.id}>{file.name}</div>
))}
</div>
)}
</div>
);
}

const styles = {
dropzone: {
border: '2px dashed #ccc',
borderRadius: 8,
padding: 40,
textAlign: 'center' as const,
},
errorContainer: {
marginTop: 16,
padding: 16,
backgroundColor: '#ffebee',
borderRadius: 8,
border: '1px solid #f44336',
},
errorTitle: {
color: '#c62828',
margin: '0 0 12px',
},
errorItem: {
marginBottom: 8,
},
errorList: {
margin: '4px 0 0',
paddingLeft: 20,
color: '#c62828',
},
acceptedFiles: {
marginTop: 16,
padding: 16,
backgroundColor: '#e8f5e9',
borderRadius: 8,
},
};