@health-ecosystem/file-upload
Version:
File upload library for Health Ecosystem applications with improved Next.js 15+ compatibility
365 lines (294 loc) • 10.7 kB
Markdown
A file upload library for Health Ecosystem applications with improved Next.js 15+ compatibility and new library management features.
- **New FileUploadLibrary Component**: Complete file management solution with library display
- **Backend API Integration**: Automatically loads files from `/api/files/files` endpoint
- **Upload Flow Redesign**: Select file → Show upload button → Upload → Reload library
- **File Actions**: Preview, select, and delete files with thumbnail support
- **Improved UX**: Better visual feedback and state management
- **Next.js 15+ Compatibility**: Updated to work with the latest Next.js versions
- **React 19 Support**: Compatible with React 19
- **TypeScript Updates**: Improved type definitions and fixed type errors
- **Bug Fixes**: Various bug fixes and performance improvements
- **Better Error Handling**: More robust error handling for uploads
- 📱 **Responsive Design** - Works on desktop and mobile
- 🖼️ **File Gallery** - Browse and select from uploaded files with thumbnails
- 🔗 **URL Upload** - Upload files directly from URLs
- 📊 **Progress Tracking** - Real-time upload progress with visual feedback
- 🔒 **Flexible Auth** - Supports both authenticated and public uploads
- 🎨 **Customizable** - Extensive styling and configuration options
- ⚡ **TypeScript** - Full TypeScript support with comprehensive types
- 🗂️ **File Management** - Preview, select, and delete files
- 🔄 **Auto Refresh** - Library automatically refreshes after uploads
```bash
npm install @health-ecosystem/file-upload@1.0.5
```
The new `FileUploadLibrary` component provides a complete file management solution that automatically integrates with your backend API.
```tsx
import React, { useState } from 'react'
import {
FileUploadLibrary,
initializeFileUploadLibrary,
FileMetadata
} from '@health-ecosystem/file-upload'
function MyComponent() {
const [selectedFile, setSelectedFile] = useState<FileMetadata | null>(null)
// Initialize with your server endpoint and access token
const { config, uploadOptions } = initializeFileUploadLibrary(
'https://api.yourdomain.com', // Your server endpoint
'your-jwt-access-token', // Your access token
{
category: 'document',
isPublic: true,
maxFileSize: 50 * 1024 * 1024, // 50MB
allowedTypes: ['image/*', 'application/pdf']
}
)
const handleFileSelect = (file: FileMetadata) => {
console.log('File selected:', file)
setSelectedFile(file)
}
return (
<div>
<FileUploadLibrary
config={config}
options={uploadOptions}
onFileSelect={handleFileSelect}
accept="image/*,application/pdf"
/>
{selectedFile && (
<div>
<h4>Selected: {selectedFile.originalFilename}</h4>
<a href={`${config.baseUrl}${selectedFile.downloadUrl}`} target="_blank">
Download
</a>
</div>
)}
</div>
)
}
```
1. **Initialization**: Provide your server endpoint and access token
2. **Auto-Load**: Component automatically fetches files from `/files?skip=0&limit=100` (relative to baseUrl)
3. **File Selection**: User selects a file to upload
4. **Upload Interface**: File selection area is replaced with upload button and progress
5. **Upload & Refresh**: After successful upload, library refreshes to show new file
6. **File Actions**: Each file shows thumbnail with preview, select, and delete actions
Your backend should implement these endpoints (relative to your baseUrl):
```
GET /files?skip=0&limit=100 - List files
POST /upload - Upload file
DELETE /files/{file_id} - Delete file
GET /files/{file_id}/download - Download file
GET /files/{file_id}/thumbnail - Get thumbnail
GET /preview/{hash} - Preview with transformations
```
**Example with baseUrl `http://localhost:8000/api/files`:**
- List files: `http://localhost:8000/api/files/files?skip=0&limit=100`
- Upload: `http://localhost:8000/api/files/upload`
- Download: `http://localhost:8000/api/files/files/{id}/download`
Expected file object structure:
```json
{
"id": "c7b5667d-0a49-4896-a74e-004a7df40261",
"original_filename": "images.png",
"file_size": 1330,
"mime_type": "image/png",
"file_category": "other",
"uploaded_by": "b93b6aad-183c-48c1-bf30-e4c54190619c",
"associated_entity_type": "other",
"associated_entity_id": null,
"is_public": true,
"created_at": "2025-07-16T06:59:14.983158",
"download_url": "/files/c7b5667d-0a49-4896-a74e-004a7df40261/download",
"thumbnail_url": "/files/c7b5667d-0a49-4896-a74e-004a7df40261/thumbnail",
"preview_url": "/preview/CRgJ_ghHmJjGHi8PBCUPPKtYHXHZlDXN"
}
```
Complete file management solution with library display and upload functionality.
```tsx
<FileUploadLibrary
config={config} // FileUploadConfig
options={uploadOptions} // UploadOptions
onFileSelect={handleFileSelect} // Callback when file is selected
multiple={false} // Allow multiple file selection
accept="*/*" // Accepted file types
className="custom-class" // Custom CSS class
style={{ border: '1px solid #ddd' }} // Custom styles
/>
```
A trigger button that opens the file upload modal.
```tsx
<FileUploadButton
config={config}
onFileSelect={(fileUrl, fileData) => console.log(fileUrl)}
options={{ category: 'document', isPublic: true }}
multiple={false}
accept="*/*"
title="Upload Files"
variant="primary" // 'primary' | 'secondary' | 'outline'
size="medium" // 'small' | 'medium' | 'large'
>
Upload Files
</FileUploadButton>
```
The main modal component with sidebar navigation and file gallery.
```tsx
<FileUploadModal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
onFileSelect={(fileUrl, fileData) => handleSelect(fileUrl, fileData)}
config={config}
options={{ category: 'document', isPublic: true }}
multiple={true}
accept="*/*"
title="File Manager"
/>
```
```typescript
const config = createFileUploadConfig(
'https://api.yourdomain.com', // Base URL
'jwt-token', // Auth token
{
maxFileSize: 50 * 1024 * 1024, // 50MB
allowedTypes: ['image/*', 'application/pdf'],
timeout: 30000,
enableRetry: true,
maxRetries: 3
}
)
```
```typescript
const options = {
category: 'document', // File category
entityType: 'patient', // Associated entity type
entityId: 'patient-uuid', // Associated entity ID
isPublic: true, // Public access (no auth required)
metadata: '{"key": "value"}' // Additional metadata
}
```
```typescript
const { config, uploadOptions } = initializeFileUploadLibrary(
'https://api.yourdomain.com', // Server endpoint
'your-jwt-token', // Access token
{
category: 'document',
isPublic: true,
maxFileSize: 50 * 1024 * 1024,
allowedTypes: ['image/*', 'application/pdf']
}
)
```
- Automatic thumbnail generation for images
- File type icons for non-image files
- Responsive grid layout
- **Select**: Choose file for use in your application
- **Preview**: Open file in new tab with transformations
- **Delete**: Remove file from library (with confirmation)
### Upload Flow
1. **File Selection Area**: Drag & drop or click to select
2. **Upload Confirmation**: Shows selected file with upload button
3. **Progress Tracking**: Real-time upload progress
4. **Library Refresh**: Automatically reloads to show new file
## Styling
### Custom Styles
```tsx
<FileUploadLibrary
config={config}
options={uploadOptions}
className="my-custom-library"
style={{
border: '2px solid #007bff',
borderRadius: '12px',
padding: '24px'
}}
/>
```
The components include CSS classes for custom styling:
- `.file-upload-library` - Main container
- `.upload-section` - Upload area
- `.file-select-area` - File selection zone
- `.upload-confirmation` - Upload button area
- `.file-library` - File grid container
- `.file-item` - Individual file card
- `.file-thumbnail` - Thumbnail container
- `.file-actions` - Action buttons container
**New Recommended Approach:**
```tsx
// Old modal-based approach
<FileUploadButton config={config} onFileSelect={handleSelect}>
Upload Files
</FileUploadButton>
// New library approach
const { config, uploadOptions } = initializeFileUploadLibrary(
'https://api.yourdomain.com',
'your-jwt-token'
)
<FileUploadLibrary
config={config}
options={uploadOptions}
onFileSelect={handleSelect}
/>
```
**Key Changes:**
- New `FileUploadLibrary` component for complete file management
- `initializeFileUploadLibrary` helper for easy setup
- Automatic integration with `/api/files/files` endpoint
- Built-in file actions (preview, select, delete)
- Improved upload flow with better UX
## Examples
See `example-library-usage.tsx` for comprehensive examples including:
- Basic file upload and library display
- Medical image upload with thumbnails
- Custom styling and theming
- Form integration with file attachments
## Browser Support
- Chrome 60+
- Firefox 60+
- Safari 12+
- Edge 79+
## License
MIT License - see LICENSE file for details.
## Changelog
### v1.0.5
- ✨ New `FileUploadLibrary` component with complete file management
- ✨ Automatic backend API integration (`/api/files/files` endpoint)
- ✨ Improved upload flow: select → upload → refresh library
- ✨ File actions: preview, select, delete with thumbnails
- ✨ `initializeFileUploadLibrary` helper function
- 🔧 Better error handling and user feedback
- 🔧 Responsive design improvements
- 📦 Updated TypeScript definitions
### v1.0.4
- ✨ Next.js 15+ compatibility
- ✨ React 19 support
- 🔧 TypeScript improvements
- 🔧 Bug fixes and performance improvements
### v1.0.3
- ✨ File Preview API with transformations
- ✨ Thumbnail support for images
- ✨ Public file preview without authentication
- ✨ URL-based file access
### v1.0.0
- Initial release with basic file upload components