tamar-community-uploader
v1.0.0
Published
File upload SDK with multipart upload, deduplication and resumable upload support
Maintainers
Readme
Community Uploader
A file upload SDK with multipart upload, deduplication, and resumable upload support.
Features
- Multipart Upload: Automatically splits large files into chunks for parallel upload
- Deduplication: MD5-based file deduplication for instant upload
- Resumable Upload: Automatically resumes interrupted uploads
- Progress Tracking: Callbacks for both MD5 calculation and upload progress
- Cancellation: Support for aborting uploads at any time
- Auto Retry: Automatic retry on network failures
- Cross Platform: Works in both browser and Node.js environments
Installation
npm install tamar-community-uploaderQuick Start
import CommunityUploader from 'tamar-community-uploader';
// Initialize
const uploader = new CommunityUploader({
baseUrl: 'https://api.example.com',
getToken: () => localStorage.getItem('token')
});
// Upload file
const result = await uploader.upload(file, {
onProgress: (percent) => console.log(`Upload: ${percent}%`),
onMD5Progress: (percent) => console.log(`MD5: ${percent}%`)
});
// Check if instant upload (deduplication hit)
if (result.deduplicated) {
console.log('File already exists, instant upload!');
}
console.log('File URL:', result.cdn_url || result.oss_url);API Reference
Constructor Options
| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| baseUrl | string | Yes | - | API base URL |
| getToken | () => string \| Promise<string> | Yes | - | Function to get auth token |
| concurrency | number | No | 3 | Number of concurrent chunk uploads |
| retryCount | number | No | 3 | Number of retries on failure |
| retryDelay | number | No | 1000 | Delay between retries (ms) |
| onLog | (message: string) => void | No | - | Log callback function |
upload(file, options?)
Upload a file with automatic MD5 calculation, deduplication, and resumable upload support.
Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| file | File \| Buffer | File to upload |
| fileName | string | Optional file name (required for Buffer) |
| options.category | string | File category: general, video, image, document |
| options.contentType | string | MIME type (auto-detected if not specified) |
| options.partSize | number | Chunk size in bytes |
| options.metadata | object | Extra metadata |
| options.onProgress | (percent) => void | Upload progress callback |
| options.onMD5Progress | (percent) => void | MD5 calculation progress callback |
| options.signal | AbortSignal | Abort signal for cancellation |
Returns
Promise<FileInfo> - File information including URLs
abortUpload(fileId)
Cancel an ongoing upload and clean up server resources.
await uploader.abortUpload(fileId);calculateMD5(file, onProgress?)
Calculate MD5 hash of a file.
const md5 = await uploader.calculateMD5(file, (percent) => {
console.log(`MD5 progress: ${percent}%`);
});getFileInfo(fileId)
Get file information by ID.
const info = await uploader.getFileInfo(fileId);listFiles(params?)
List user's files with pagination.
const result = await uploader.listFiles({
category: 'video',
status: 'confirmed',
page: 1,
page_size: 20
});deleteFile(fileId)
Soft delete a file.
await uploader.deleteFile(fileId);Usage with AbortController
const controller = new AbortController();
// Start upload
const uploadPromise = uploader.upload(file, {
signal: controller.signal,
onProgress: (percent) => console.log(`${percent}%`)
});
// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);
try {
await uploadPromise;
} catch (error) {
if (error.name === 'AbortError') {
console.log('Upload cancelled');
}
}React Hook Example
import { useState, useCallback, useRef } from 'react';
import CommunityUploader from 'tamar-community-uploader';
export function useUploader(options) {
const [status, setStatus] = useState('idle');
const [progress, setProgress] = useState(0);
const controllerRef = useRef(null);
const uploader = useMemo(() => new CommunityUploader(options), []);
const upload = useCallback(async (file) => {
controllerRef.current = new AbortController();
setStatus('uploading');
try {
const result = await uploader.upload(file, {
signal: controllerRef.current.signal,
onProgress: setProgress
});
setStatus('success');
return result;
} catch (error) {
setStatus(error.name === 'AbortError' ? 'cancelled' : 'error');
throw error;
}
}, [uploader]);
const cancel = useCallback(() => {
controllerRef.current?.abort();
}, []);
return { status, progress, upload, cancel };
}License
MIT
