Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Tus Php Laravel Package

ankitpokhrel/tus-php

PHP server/client implementation of the tus resumable upload protocol. Supports large, chunked uploads with pause/resume, retries, and offsets; integrates with popular PHP frameworks and storage backends, offering configurable middleware, events, and validation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package:
    composer require ankitpokhrel/tus-php
    
  2. Publish the config (optional but recommended):
    php artisan vendor:publish --provider="AnkitPokhrel\Tus\TusServiceProvider" --tag="tus-config"
    
  3. Configure storage backend (e.g., filesystem or s3):
    // config/tus.php
    'storage' => [
        'driver' => 'local',
        'path' => storage_path('app/tus-uploads'),
    ],
    
  4. Add routes in routes/web.php:
    use AnkitPokhrel\Tus\TusRoute;
    
    TusRoute::upload('upload', [
        'store' => 'AnkitPokhrel\Tus\Storage\FileSystem',
        'path' => storage_path('app/tus-uploads'),
    ]);
    
  5. Test with a client (e.g., tus-js-client):
    const upload = new tus.Upload(file, {
        endpoint: '/upload',
        metadata: { filename: 'test.pdf' },
        retryDelays: [0, 1000, 3000, 5000]
    });
    upload.start();
    

First Use Case: Handling Large File Uploads

  • Use the package to replace traditional file uploads for files >100MB.
  • Example: Let users upload videos/resumes without timeout errors.
  • Key config: Set max_size in tus.php (e.g., max_size => 5 * 1024 * 1024 * 1024 for 5GB).

Implementation Patterns

Core Workflow: Upload Lifecycle

  1. Initiate Upload:
    • Client sends OPTIONS to /upload → Server responds with Upload-Offset: 0.
    • Client starts uploading chunks with Upload-Length header.
  2. Pause/Resume:
    • Client pauses by sending Upload-Offset at current position.
    • Resumes by re-sending chunks from the offset.
  3. Completion:
    • Final chunk sent → Server triggers onComplete hook (e.g., move file to final location).

Laravel-Specific Patterns

  1. Middleware Integration:
    // app/Http/Kernel.php
    'tus' => [
        \AnkitPokhrel\Tus\Middleware\CheckUploadSize::class,
        \AnkitPokhrel\Tus\Middleware\CheckUploadMethod::class,
    ],
    
  2. Event Listeners:
    • Listen to tus.upload.complete to process files post-upload:
    // app/Listeners/HandleUploadComplete.php
    public function handle(UploadComplete $event) {
        $file = $event->getFile();
        // Move to S3, generate thumbnails, etc.
    }
    
  3. Custom Storage Backends:
    • Extend AnkitPokhrel\Tus\Storage\StorageInterface for S3, database, etc.:
    class S3Storage implements StorageInterface {
        public function storeChunk($uploadId, $chunk) { ... }
        public function finalize($uploadId, $metadata) { ... }
    }
    

Integration Tips

  • Frontend: Use tus-js-client or tus-resumer for browsers.
  • Progress Tracking: Expose upload progress via:
    TusRoute::progress('progress/{uploadId}', [
        'store' => 'AnkitPokhrel\Tus\Storage\FileSystem',
    ]);
    
  • Metadata: Attach custom metadata (e.g., user ID, file type):
    upload.setHeader('Upload-Metadata', JSON.stringify({
        user_id: 123,
        file_type: 'video'
    }));
    

Gotchas and Tips

Common Pitfalls

  1. CORS Issues:
    • Ensure your server sends Access-Control-Allow-Origin headers. Use middleware:
    Header::set('Access-Control-Allow-Origin', '*');
    Header::set('Access-Control-Allow-Methods', 'OPTIONS, POST, PATCH, DELETE');
    
  2. File Locking:
    • Concurrent uploads to the same file may cause conflicts. Use upload_id to isolate files.
  3. Memory Limits:
    • Large chunks (>100MB) may hit PHP’s memory_limit. Adjust or stream chunks directly to storage.

Debugging

  • Enable Logging:
    // config/tus.php
    'debug' => env('APP_DEBUG', false),
    
  • Check Upload Status:
    curl -X OPTIONS http://your-app/upload -H "Upload-Offset: 0"
    
  • Common Errors:
    • 400 Bad Request: Invalid headers (e.g., missing Upload-Length).
    • 403 Forbidden: Missing Upload-Metadata or size limits exceeded.

Extension Points

  1. Custom Hooks:
    • Override onCreate, onUpload, onComplete in your storage backend:
    class CustomStorage extends FileSystem {
        public function onComplete($uploadId, $metadata) {
            // Add post-processing logic
            parent::onComplete($uploadId, $metadata);
        }
    }
    
  2. Validation:
    • Validate metadata or file types via onCreate:
    public function onCreate($uploadId, $metadata) {
        if (!in_array($metadata['file_type'], ['video', 'image'])) {
            throw new \RuntimeException('Invalid file type');
        }
    }
    
  3. Cleanup:
    • Implement onTerminate to delete partial uploads:
    public function onTerminate($uploadId) {
        $this->delete($uploadId);
    }
    

Performance Tips

  • Chunk Size: Optimal chunk size is 5MB–100MB (balance between latency and overhead).
  • Storage Backend: For S3, use AWSS3 adapter with stream_wrappers for direct uploads.
  • Queue Jobs: Offload post-upload processing (e.g., video encoding) to Laravel queues:
    event(new UploadComplete($uploadId, $metadata));
    // Dispatch to queue in onComplete
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager