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

Uploader Bundle Laravel Package

oneup/uploader-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require oneup/uploader-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Oneup\UploaderBundle\OneupUploaderBundle::class => ['all' => true],
    ];
    
  2. Configure Storage Edit config/packages/oneup_uploader.yaml:

    oneup_uploader:
        mappings:
            my_uploads:
                frontend: dropzone # or plupload, jquery_file_upload, etc.
                storage: gaufrette
                gaufrette:
                    service: my_gaufrette_adapter
                orphanage: true
    

    Register a Gaufrette adapter (e.g., services.yaml):

    services:
        my_gaufrette_adapter:
            class: Gaufrette\Filesystem
            factory: ['Gaufrette\FilesystemMap', 'build']
            arguments: ['%kernel.project_dir%/public/uploads']
    
  3. First Upload Route

    // src/Controller/UploadController.php
    use Oneup\UploaderBundle\Handler\HandlerRegistry;
    use Symfony\Component\HttpFoundation\Request;
    
    class UploadController extends AbstractController
    {
        public function upload(Request $request, HandlerRegistry $handlerRegistry)
        {
            $handler = $handlerRegistry->getHandler('my_uploads');
            $handler->upload($request);
    
            return $this->json(['success' => true]);
        }
    }
    

    Route it in config/routes.yaml:

    upload:
        path: /upload
        controller: App\Controller\UploadController::upload
        methods: POST
    
  4. Frontend Integration Use the Dropzone example or another supported library. Key config:

    Dropzone.options.myDropzone = {
        url: '/upload',
        paramName: 'file', // Default, but ensure it matches backend
        maxFilesize: 5,    // MB
        autoProcessQueue: true,
    };
    

Implementation Patterns

Core Workflows

  1. Handler-Based Processing

    • Use HandlerRegistry to dynamically resolve handlers by mapping name (e.g., 'my_uploads').
    • Chain middleware for validation, transformation, or metadata enrichment:
      $handler->addMiddleware(new MyCustomMiddleware());
      
  2. Storage Abstraction

    • Gaufrette/Flysystem: Leverage adapters for cloud storage (S3, Rackspace) or local filesystems. Example S3 setup:
      gaufrette:
          service: my_s3_adapter
      services:
          my_s3_adapter:
              class: Gaufrette\Filesystem
              factory: ['Gaufrette\Adapter\AwsS3', 'fromPath']
              arguments: ['my-bucket']
      
    • Orphanage: Enable cleanup of failed uploads via orphanage: true in config.
  3. Chunked Uploads

    • Configure chunk size in frontend (e.g., Dropzone chunking: true) and backend:
      oneup_uploader:
          mappings:
              my_uploads:
                  chunk_size: 5MB # Adjust based on server limits
      
    • Handle chunks via HandlerRegistry (automatically managed by bundle).
  4. Progress Tracking

    • Use PHP’s session.upload_progress (PHP ≥5.4) or implement custom progress middleware:
      $handler->addMiddleware(new ProgressTrackingMiddleware());
      
  5. Metadata Handling

    • Access uploaded file metadata (size, MIME, etc.) via:
      $file = $handler->getFile();
      $metadata = $file->getMetadata();
      

Integration Tips

  1. Validation

    • Use Symfony’s Validator or custom middleware:
      $handler->addMiddleware(new FileTypeMiddleware(['jpg', 'png']));
      
    • Example: Restrict file types via YAML:
      oneup_uploader:
          mappings:
              my_uploads:
                  allowed_mime_types: ['image/jpeg', 'image/png']
      
  2. Dynamic Mappings

    • Register mappings programmatically (e.g., per-user uploads):
      $handlerRegistry->addMapping('user_'.$userId, [
          'frontend' => 'dropzone',
          'storage' => 'gaufrette',
          // ...
      ]);
      
  3. Event Listeners

    • Subscribe to upload events (e.g., oneup_uploader.pre_upload):
      // src/EventListener/UploadListener.php
      public function onPreUpload(PreUploadEvent $event) {
          $file = $event->getFile();
          // Modify file metadata or path
      }
      
      Register in services.yaml:
      services:
          App\EventListener\UploadListener:
              tags:
                  - { name: kernel.event_listener, event: oneup_uploader.pre_upload }
      
  4. Testing

    • Mock HandlerRegistry and File objects:
      $handler = $this->createMock(HandlerInterface::class);
      $handler->method('upload')->willReturn(true);
      $registry = $this->createMock(HandlerRegistry::class);
      $registry->method('getHandler')->willReturn($handler);
      

Gotchas and Tips

Pitfalls

  1. Frontend-Backend Mismatch

    • Issue: Upload fails silently if paramName (e.g., file) doesn’t match frontend config.
    • Fix: Explicitly set in both frontend (e.g., Dropzone paramName: 'file') and backend (default is 'file').
  2. Chunked Uploads and Orphanage

    • Issue: Partial chunks may linger in orphanage if upload is interrupted.
    • Fix: Set orphanage_lifetime in config (default: 1 day):
      oneup_uploader:
          orphanage_lifetime: 3600 # 1 hour
      
  3. Gaufrette/Flysystem Permissions

    • Issue: "Permission denied" errors when writing to storage.
    • Fix: Ensure the storage directory is writable by the web server user (e.g., chown -R www-data:www-data /path/to/uploads).
  4. Session Upload Progress

    • Issue: session.upload_progress requires PHP ≥5.4 and session.upload_progress.enabled=1 in php.ini.
    • Fix: Fall back to custom middleware if unsupported.
  5. Large File Handling

    • Issue: PHP upload_max_filesize or post_max_size limits exceeded.
    • Fix: Adjust in php.ini and configure chunking:
      oneup_uploader:
          mappings:
              my_uploads:
                  chunk_size: 2MB
      

Debugging

  1. Log Upload Events

    • Enable debug mode and log events:
      $handler->addMiddleware(new LoggingMiddleware());
      
    • Custom middleware example:
      class LoggingMiddleware implements MiddlewareInterface {
          public function handle(File $file, callable $next) {
              \Log::debug('Upload started', ['file' => $file->getClientOriginalName()]);
              return $next($file);
          }
      }
      
  2. Check Orphanage

    • List orphaned files:
      $orphanage = $handlerRegistry->getOrphanage('my_uploads');
      $orphans = $orphanage->list();
      
  3. Validate Frontend Requests

    • Use browser dev tools to inspect:
      • Network tab: Check request payload (e.g., file field).
      • Console: Look for JS errors (e.g., Dropzone error events).

Extension Points

  1. Custom Frontend

    • Implement Oneup\UploaderBundle\Handler\Frontend\FrontendInterface for unsupported libraries.
    • Example: Custom Uploader Docs.
  2. Storage Adapters

    • Extend Gaufrette/Flysystem with custom adapters (e.g., for local paths with symlinks):
      class CustomAdapter extends Gaufrette\Adapter\Local {
          public function write($path, $content) {
              // Custom logic (e.g., symlink handling)
              return parent::write($path, $content);
          }
      }
      
  3. Middleware Pipeline

    • Add custom logic before/after upload:
      $handler->addMiddleware(new class implements MiddlewareInterface {
          public function handle(File $file, callable $next) {
              // Pre-upload logic
              $file = $next($file);
              // Post-upload logic
              return $file;
          }
      });
      
  4. File Metadata

    • Extend `Oneup\U
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware