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

Far Symfony2 Jquery Upload Laravel Package

anatoliynyatin/far-symfony2-jquery-upload

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require anatoliynyatin/far-symfony2-jquery-upload "~1"
    

    (Note: The package name in the composer.json is anatoliynyatin/far-symfony2-jquery-upload, but the README uses faparicior/far-symfony2-jquery-upload. Use the correct namespace in AppKernel.php.)

  2. Enable the Bundle Add to app/AppKernel.php:

    new \anatoliynyatin\FARSymfony2UploadBundle\FARSymfony2UploadBundle(),
    
  3. Configure Routing Add to app/config/routing.yml:

    far_symfony2_upload:
        resource: "@FARSymfony2UploadBundle/Controller/"
        type: annotation
        prefix: "/farupload"
    
  4. Basic Configuration Add to app/config/config.yml:

    far_symfony2_upload:
        prefix: "farupload"
        temp_path: "%kernel.root_dir%/../web/tmp"
        file_extensions_allowed: ["jpg", "png", "gif"]
    
  5. Enable OneUpFlySystem Follow OneUpFlySystemBundle setup for filesystem adapters.

  6. First Use Case Initialize BlueImp jQuery File Upload in your frontend:

    $("#fileupload").fileupload({
        url: "{{ path('farsymfony2upload_default_upload', {'id_session': 'unique_id_here'}) }}",
        dataType: 'json',
        // ... other options
    });
    

Implementation Patterns

Workflow: File Upload Pipeline

  1. Frontend Setup

    • Use BlueImp’s jQuery File Upload plugin with the bundle’s endpoint.
    • Pass a unique id_session (e.g., UUID or model ID) to track uploads.
  2. Temporary Storage

    • Files land in temp_path (e.g., web/tmp) under a structured path: {php_session}/{id_session}/{filename}.
    • Example: abc123/456/unique_filename.jpg.
  3. Backend Processing

    • Fetch Files: Use getListFilesLocal($php_session, $id_session) to retrieve uploaded files.
    • Prepare Destinations: Modify pathDest, dirnameDest, etc., in the returned array to define where files should move.
    • Sync Files: Call syncFilesLocalRemote($files, $overwrite) to move files to the permanent filesystem (e.g., S3, local storage).
    • Cleanup: Use deleteFilesLocal($files) to remove temp files post-success.
    // Example: Save files to a user's profile directory
    $files = $FARUpload->getListFilesLocal($sessionId, $userId);
    foreach ($files['files'] as &$file) {
        $file['dirnameDest'] = "users/{$userId}/uploads";
    }
    $result = $FARUpload->syncFilesLocalRemote($files, false);
    $FARUpload->deleteFilesLocal($result['files']);
    
  4. Thumbnail Generation

    • Configure thumbnail_driver (e.g., gd, imagine) and thumbnail_size in config.yml.
    • Thumbnails auto-generate in {temp_path}/{thumbnail_directory_prefix} during syncFilesLocalRemote.
  5. Error Handling

    • Validate file_extensions_allowed, max_file_size, and max_files_upload in the frontend and backend.
    • Return JSON errors from the /farupload/upload endpoint:
      { "error": "File type not allowed" }
      

Integration Tips

  • Symfony Forms: Use the bundle for file uploads in forms by:
    1. Adding a hidden field for id_session (e.g., tied to an entity ID).
    2. Triggering the upload via JavaScript on form submission.
  • Entity Associations: Link uploaded files to Doctrine entities by storing the id_session in a FileUpload table.
  • Asynchronous Processing: Use Symfony’s Messenger component to defer syncFilesLocalRemote to a worker (e.g., for large files).
  • Custom Validation: Extend the bundle’s FARUpload service to add pre-sync validation (e.g., duplicate filenames):
    $FARUpload->addPreSyncValidator(function ($files) {
        foreach ($files['files'] as $file) {
            if (file_exists($file['pathDest'])) {
                throw new \RuntimeException("File already exists");
            }
        }
    });
    

Gotchas and Tips

Pitfalls

  1. Session Mismatch

    • Issue: Files disappear because the php_session or id_session is incorrect.
    • Fix: Log $php_session and id_session in the upload endpoint to debug mismatches.
    • Tip: Use a consistent id_session generator (e.g., UUID) across frontend/backend.
  2. Filesystem Permissions

    • Issue: syncFilesLocalRemote fails silently if the destination directory lacks write permissions.
    • Fix: Ensure OneUpFlySystemBundle adapters have correct permissions. For local storage:
      chmod -R 775 %kernel.root_dir%/../web/tmp
      
  3. Thumbnail Generation

    • Issue: Thumbnails fail if imagine or gd is misconfigured.
    • Fix: Verify thumbnail_driver is installed (php -m | grep gd or imagine). Update config.yml:
      far_symfony2_upload:
          thumbnail_driver: "gd"  # or "imagine"
      
  4. Route Conflicts

    • Issue: The /farupload prefix may clash with existing routes.
    • Fix: Customize the prefix in both routing.yml and config.yml.
  5. Large File Handling

    • Issue: Timeouts or memory limits during syncFilesLocalRemote for large files (>100MB).
    • Fix:
      • Increase PHP limits (memory_limit, max_execution_time).
      • Use chunked uploads (BlueImp supports this natively).
      • Offload to a queue (e.g., Symfony Messenger + Doctrine Messages).
  6. File Extension Spoofing

    • Issue: Users bypass file_extensions_allowed by renaming files (e.g., image.jpg.php).
    • Fix: Validate MIME types server-side:
      $mime = mime_content_type($file['pathOrig']);
      if (!in_array($mime, ['image/jpeg', 'image/png'])) {
          throw new \RuntimeException("Invalid file type");
      }
      

Debugging Tips

  1. Log File Paths Add debug logs in your saveAction to inspect file paths:

    $this->get('logger')->debug('Temp files:', ['files' => $files]);
    
  2. Verify Filesystem Adapters Dump the configured adapters to ensure they’re correct:

    $this->get('oneup_flysystem.filesystem_manager')->getFilesystem('remote_filesystem')->listContents('/');
    
  3. Check BlueImp Console Enable BlueImp’s debug console to inspect upload progress:

    $("#fileupload").fileupload({
        // ...
        debug: true
    });
    
  4. Test with debug:router Verify routes are registered:

    php bin/console debug:router | grep farupload
    

Extension Points

  1. Custom File Processing Override the FARUpload service to add pre/post-sync logic:

    # app/config/services.yml
    services:
        app.far_upload:
            class: anatoliynyatin\FARSymfony2UploadBundle\Service\FARUpload
            arguments:
                - "@oneup_flysystem.filesystem_manager"
                - "@session"
            calls:
                - [addPreSyncValidator, ["@app.pre_sync_validator"]]
    
  2. Dynamic Configuration Load far_symfony2_upload settings from a database or API:

    $config = $this->get('app.config_loader')->load('upload_settings');
    $this->get('far_symfony2_upload_bundle.far_symfony2_upload_lib.service')->setConfig($config);
    
  3. Event Listeners Dispatch events before/after file sync:

    // In your controller
    $this->get('event_dispatcher')->dispatch(
        'far_upload.pre_sync',
        new FarUploadEvent($files, $php_session, $id_session)
    );
    
  4. Custom Storage Drivers Extend OneUpFlySystemBundle to support additional backends (e.g., Google Cloud Storage):

    // Create a custom adapter and register it in oneup_flysystem.adapters
    

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