開始使用 Dropup
Dropup 是一個輕量級、無樣式的 React 檔案上傳函式庫,讓您完全控制 UI,同時處理所有複雜的上傳邏輯。
為什麼選擇 Dropup?
- 🪶 輕量級 - 核心套件壓縮後僅約 10KB
- 🎨 無樣式設計 - 透過基於 hooks 的 API 完全控制您的 UI
- 📁 拖放功能 - 內建拖放支援
- 📊 進度追蹤 - 每個檔案的即時上傳進度
- 🔄 分塊上傳 - 將大型檔案分割以實現可靠的上傳
- ☁️ 雲端就緒 - S3、GCS 和 Azure 的預建輔助工具
- 🖼️ 圖片處理 - 內建壓縮和預覽生成
- 📱 跨平台 - 支援 React DOM 和 React Native
- 🔒 TypeScript - 完整的 TypeScript 支援
安裝
使用您喜歡的套件管理器安裝 Dropup:
npm install @samithahansaka/dropup
對等相依性
Dropup 需要 React 16.8 或更高版本(用於 hooks 支援):
npm install react
快速開始
這是一個簡單的範例,幫助您開始:
import { useDropup } from '@samithahansaka/dropup';
function FileUploader() {
const {
files,
state,
actions,
getDropProps,
getInputProps
} = useDropup({
accept: 'image/*',
maxSize: 10 * 1024 * 1024, // 10MB
multiple: true,
});
return (
<div>
{/* 拖放區域 */}
<div
{...getDropProps()}
style={{
border: state.isDragging ? '2px dashed blue' : '2px dashed gray',
padding: 40,
textAlign: 'center',
cursor: 'pointer',
}}
>
<input {...getInputProps()} />
<p>將檔案拖放到此處,或點擊選擇</p>
</div>
{/* 檔案列表 */}
<ul>
{files.map((file) => (
<li key={file.id}>
{file.name} - {file.status}
{file.status === 'uploading' && ` (${file.progress}%)`}
<button onClick={() => actions.remove(file.id)}>移除</button>
</li>
))}
</ul>
{/* 上傳按鈕 */}
{files.length > 0 && (
<button onClick={() => actions.upload()}>
上傳全部
</button>
)}
</div>
);
}
核心概念
1. useDropup Hook
useDropup hook 是主要的進入點。它返回建立檔案上傳 UI 所需的一切:
const {
files, // 包含狀態、進度等的檔案陣列
state, // 整體狀態(isDragging、isUploading、progress)
actions, // 上傳、移除、取消、重置的方法
getDropProps, // 拖放區域元素的屬性
getInputProps, // 隱藏檔案輸入的屬性
} = useDropup(options);
2. 檔案物件
files 陣列中的每個檔案包含:
{
id: string; // 唯一識別碼
file: File; // 原始 File 物件
name: string; // 檔案名稱
size: number; // 檔案大小(位元組)
type: string; // MIME 類型
preview?: string; // 預覽 URL(用於圖片)
status: 'idle' | 'uploading' | 'complete' | 'error';
progress: number; // 上傳進度(0-100)
error?: Error; // 上傳失敗時的錯誤物件
uploadedUrl?: string; // 成功上傳後的 URL
}
3. 操作方法
actions 物件提供控制上傳的方法:
actions.upload(fileIds?) // 開始上傳(全部或特定檔案)
actions.cancel(fileId?) // 取消上傳
actions.remove(fileId) // 從列表中移除檔案
actions.reset() // 清除所有檔案
actions.retry(fileIds?) // 重試失敗的上傳
設定上傳
要啟用實際上傳,請提供上傳設定:
const { files } = useDropup({
upload: {
url: '/api/upload',
method: 'POST',
headers: {
'Authorization': 'Bearer token',
},
},
autoUpload: true, // 新增檔案時自動上傳
});