@beyonk/uploader
v8.0.3
Published
A complete file upload system.
Keywords
Readme
@beyonk/uploader
A complete file upload system.
Components
FileManager
Core state management for file handling with validation, error tracking, and hooks.
UploadAdapter
Handles upload operations with the backend API. This is exclusively built to be used for Beyonk's upload GCP function. Another adapter can be written and composed with FileManager.
Multi
UI component for multiple file uploads with drag-and-drop interface and preview thumbnails.
Single
UI component for single file upload with preview thumbnail.
Quick Start
<script>
import { FileManager, UploadAdapter, Multi, Single } from '@beyonk/uploader'
const uploadAdapter = new UploadAdapter({
uploadUrl: 'https://api.example.com/upload',
cdnUrl: 'https://cdn.example.com',
folderPath: 'images',
onUploadComplete: (results) => {
for (const result of results) {
if (result.success) {
fileManager.swap(result.file.id, result.serverFile)
} else {
fileManager.setFileError(result.file.id, result.error)
}
}
}
})
const fileManager = new FileManager({
maxFiles: 5,
onAddFiles: async (files) => {
await uploadAdapter.addFiles(files)
}
})
</script>
<!-- For multiple file uploads -->
<Multi {fileManager} />
<!-- Or for single file upload -->
<Single {fileManager} />Tailwind CSS Configuration
If you're using Tailwind CSS, you need to include the package's component files in your Tailwind content configuration so that the classes used by the uploader components are included in your build:
// tailwind.config.js
const config = {
content: [
'./src/**/*.{html,svelte}',
'./node_modules/@beyonk/uploader/dist/**/*.{html,svelte,js}'
],
// ... rest of your config
}FileManager Options
const fileManager = new FileManager({
maxFiles: 5, // Maximum number of files
maxFileSize: 5 * 1024 * 1024, // 5MB limit
acceptedTypes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/heic'],
countRemoteFiles: true, // Include remote files in limit
onAddFiles: async (files) => { // Hook for new files
await uploadFiles(files)
},
onFileRemove: (file) => { // Hook for file removal
// Handle file removal in UI
},
onUploadErrorsChange: (hasErrors) => { // Hook for upload error state changes
// Handle upload error state changes
}
})UploadAdapter Options
const uploadAdapter = new UploadAdapter({
// Required: Upload endpoint URL
uploadUrl: 'https://api.example.com/upload',
// Required: CDN base URL
cdnUrl: 'https://cdn.example.com',
// Required: Folder path for uploads
folderPath: 'images',
// Lifecycle hooks
onUploadStart: (files) => {
// Clear any existing errors
for (const file of files) {
if (file.hasError) {
fileManager.clearFileError(file.id)
}
}
},
onUploadComplete: (results) => {
// Handle successful uploads and errors
for (const result of results) {
if (result.success) {
fileManager.swap(result.file.id, result.serverFile)
} else {
fileManager.setFileError(result.file.id, result.error)
}
}
},
onUploadError: (error, files) => {
// Handle upload failures
fileManager.setGlobalError('Upload failed. Please try again.')
}
})File Operations
// Add files programmatically
const success = await fileManager.addFiles(fileList)
// Add remote files (already uploaded) - requires uploadAdapter instance
fileManager.addRemoteFile(uploadAdapter.buildCdnUrl('images/image.jpg'))
// Remove files
fileManager.removeFile(fileId)
// Get final files list for form submission
const files = fileManager.files
.filter(file => file.type === 'url' && file.uploaded)
.map(file => ({
path: UploadAdapter.getPathFromUrl(file.content),
uploadedAt: new Date()
}))State Management
// File state
fileManager.files // All files
fileManager.hasUploadsInProgress
fileManager.allUploadsComplete
fileManager.hasErrors
// Error handling
fileManager.globalError // Global error message
fileManager.setGlobalError(msg)
fileManager.clearGlobalError()
fileManager.setFileError(id, error, errorType)
fileManager.clearFileError(id)
// Error types (import from package)
import { ERROR_TYPES } from '@beyonk/uploader'
// ERROR_TYPES.VALIDATION_SIZE
// ERROR_TYPES.VALIDATION_FORMAT
// ERROR_TYPES.VALIDATION_EMPTY
// ERROR_TYPES.LIMIT_EXCEEDED
// ERROR_TYPES.UPLOAD_FAILED
// ERROR_TYPES.GENERALForm Integration with Cleanup
<script>
// Track unsaved changes
const hasUnsavedChanges = $derived(
fileManager.files.some(f => f.type === 'url' && f.isNewUpload)
)
function handleBeforeUnload(event) {
if (hasUnsavedChanges) {
event.preventDefault()
event.returnValue = 'You have unsaved changes.'
}
}
</script>
<svelte:window
onbeforeunload={handleBeforeUnload}
/>Backend Integration
The system sends upload requests via FormData:
// Upload request format
const formData = new FormData()
formData.append('files', JSON.stringify([
{ fileId: 'file123', folderPath: 'images' }
]))
formData.append('file', fileBlob)
// ... additional files appended as 'file'
// Expected response format
{
uploads: [
{
fileId: 'file123',
success: true,
url: 'cdn.example.com/images/file123.jpg',
originalFileName: 'photo.jpg'
}
]
}Features
- Upload on drop: Files upload immediately when added
- Batch operations: Multiple files uploaded together
- Error handling: File-level and global error states with ERROR_TYPES
- Status tracking: Upload status monitoring
- Image previews: Automatic thumbnail generation (including HEIC support)
- File validation: Size, type, and count limits
- Retry mechanism: Failed uploads can be retried
- Hook-based: Extensible via onAddFiles/onFileRemove/onUploadErrorsChange hooks
- Dual UI components: Multi-file and single-file upload components
Developing
Once you've created a project and installed dependencies with npm install (or pnpm install or yarn), start a development server:
pnpm dev
# or start the server and open the app in a new browser tab
pnpm dev -- --openEverything inside src/lib is part of your library, everything inside src/routes can be used as a showcase or preview app.
Building
To build your library:
pnpm packTo create a production version of your showcase app:
pnpm run buildYou can preview the production build with npm run preview.
To deploy your app, you may need to install an adapter for your target environment.
Publishing
This package uses Changesets for version management.
To publish a new version:
Create a changeset describing your changes:
pnpm changesetFollow the prompts to select the package, version type (patch/minor/major), and describe the changes.
Commit the generated
.changesetdirectory along with your changes:git add .changeset git commit -m "Add changeset"Push your branch and wait for the automated changeset PR to be opened, then merge it.
After merging, the package version and
CHANGELOG.mdwill be automatically updated. Then publish to npm manually:pnpm --filter @beyonk/uploader publish
