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

Al Valum Uploader Bundle Laravel Package

alphalemon/al-valum-uploader-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    git clone git://github.com/alphalemon/AlValumUploaderBundle.git vendor/bundles/AlphaLemon/AlValumUploaderBundle
    

    Update app/autoload.php to register the namespace:

    $loader->registerNamespaces(array(
        'AlphaLemon' => __DIR__.'/../vendor/bundles',
    ));
    
  2. Register Bundle (in AppKernel.php):

    public function registerBundles()
    {
        $bundles = [
            // ...
            new AlphaLemon\AlValumUploaderBundle\AlValumUploaderBundle(),
        ];
    }
    
  3. Configure Assetic (in config.yml):

    assetic:
        filters:
            yui_js:
                jar: %kernel.root_dir%/Resources/java/yuicompressor.jar
            yui_css:
                jar: %kernel.root_dir%/Resources/java/yuicompressor.jar
    

    Download yuicompressor.jar from YUI Compressor and place it in app/Resources/java/.

  4. Install Assets:

    php app/console assets:install web --symlink
    

First Use Case

Integrate the uploader into a Twig template:

{% block stylesheets %}
    {{ parent() }}
    {{ asset('bundles/alvalumuploader/css/valum.css') }}
{% endblock %}

{% block javascripts %}
    {{ parent() }}
    {{ asset('bundles/alvalumuploader/js/valum.js') }}
    <script>
        $(document).ready(function() {
            $('#file-uploader').valumUploader({
                uploadUrl: '{{ path('upload_endpoint') }}',
                allowedExtensions: ['jpg', 'png', 'gif'],
                maxFileSize: 5242880 // 5MB
            });
        });
    </script>
{% endblock %}

Create a controller endpoint (src/AlphaLemon/AlValumUploaderBundle/Controller/UploadController.php):

namespace AlphaLemon\AlValumUploaderBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class UploadController extends Controller
{
    public function uploadAction(Request $request)
    {
        $file = $request->files->get('file');
        $uploadDir = $this->get('kernel')->getRootDir().'/../web/uploads/';

        $file->move($uploadDir, $file->getClientOriginalName());

        return new Response(json_encode([
            'success' => true,
            'file' => $file->getClientOriginalName()
        ]));
    }
}

Route it in routing.yml:

al_valum_uploader_upload:
    path:     /upload
    defaults: { _controller: AlphaLemonAlValumUploaderBundle:Upload:upload }

Implementation Patterns

Common Workflows

  1. Basic File Upload:

    • Use the Valum uploader widget in Twig templates with predefined configurations.
    • Example:
      <div id="file-uploader" data-upload-url="{{ path('upload_endpoint') }}"></div>
      
  2. Dynamic Configuration:

    • Pass dynamic settings via JavaScript:
      $('#file-uploader').valumUploader({
          uploadUrl: '/dynamic-upload-endpoint',
          allowedExtensions: ['pdf', 'docx'],
          maxFileSize: 10485760, // 10MB
          onComplete: function(response) {
              console.log('Uploaded:', response);
          }
      });
      
  3. Server-Side Handling:

    • Extend the UploadController to handle file processing (e.g., validation, storage, metadata extraction).
    • Example with validation:
      public function uploadAction(Request $request)
      {
          $file = $request->files->get('file');
          $allowedExtensions = ['jpg', 'png', 'gif'];
          $maxSize = 5 * 1024 * 1024; // 5MB
      
          if (!$file || !in_array(strtolower($file->getClientOriginalExtension()), $allowedExtensions)) {
              return new Response(json_encode(['success' => false, 'error' => 'Invalid file type']), 400);
          }
      
          if ($file->getSize() > $maxSize) {
              return new Response(json_encode(['success' => false, 'error' => 'File too large']), 400);
          }
      
          // Proceed with upload logic...
      }
      
  4. Chunked Uploads:

    • Configure Valum for chunked uploads (useful for large files):
      $('#file-uploader').valumUploader({
          chunkSize: 1024 * 1024, // 1MB chunks
          uploadUrl: '/chunked-upload'
      });
      
    • Server-side: Use a library like league/flysystem to handle chunked uploads.
  5. Integration with Doctrine:

    • Save file metadata to a database entity:
      $uploadedFile = new UploadedFile();
      $uploadedFile->setName($file->getClientOriginalName());
      $uploadedFile->setPath($file->getPath());
      $uploadedFile->setSize($file->getSize());
      $uploadedFile->setMimeType($file->getMimeType());
      $uploadedFile->setUser($this->getUser());
      
      $em = $this->getDoctrine()->getManager();
      $em->persist($uploadedFile);
      $em->flush();
      

Integration Tips

  • Assetic Integration: Ensure yuicompressor.jar is correctly configured in config.yml for minification. Example Assetic config for Valum:

    assetic:
        bundles: [AlphaLemonAlValumUploaderBundle]
        assets:
            valum_js:
                inputs:
                    - '@AlphaLemonAlValumUploaderBundle/Resources/public/js/valum.js'
                filters: [yui_js]
            valum_css:
                inputs:
                    - '@AlphaLemonAlValumUploaderBundle/Resources/public/css/valum.css'
                filters: [yui_css]
    
  • Custom Templates: Override Valum templates by extending the bundle’s resources:

    {% extends 'AlphaLemonAlValumUploaderBundle::default/template.html.twig' %}
    {% block valum_template %}
        {{ parent() }}
        <!-- Custom HTML/JS -->
    {% endblock %}
    
  • Event Listeners: Dispatch events for upload progress or completion using Symfony’s event system:

    // In services.yml
    services:
        al_valum_uploader.listener:
            class: AppBundle\EventListener\UploadListener
            tags:
                - { name: kernel.event_listener, event: al_valum_uploader.upload_complete, method: onUploadComplete }
    

Gotchas and Tips

Pitfalls

  1. Missing yuicompressor.jar:

    • Symptom: JavaScript/CSS assets fail to load or are unminified.
    • Fix: Download yuicompressor.jar and place it in app/Resources/java/. Ensure the path in config.yml is correct.
  2. CORS Issues:

    • Symptom: Uploads fail with CORS errors if the frontend and backend are on different domains.
    • Fix: Configure CORS headers in your server (e.g., Apache/Nginx) or use a proxy.
  3. File Size Limits:

    • Symptom: Large files fail silently or with HTTP 500 errors.
    • Fix: Increase upload_max_filesize and post_max_size in php.ini. For chunked uploads, ensure the server can handle partial requests.
  4. Bundle Not Loading:

    • Symptom: Valum assets or routes are unavailable.
    • Fix: Verify the bundle is registered in AppKernel.php and the namespace is included in autoload.php.
  5. Symfony 2.1 Dependency:

    • Symptom: Compatibility issues with newer Symfony versions.
    • Fix: Use a compatibility layer (e.g., symfony/symfony:2.1.*) or fork the bundle for updates.

Debugging

  • Check Valum Console Logs: Open browser dev tools (F12) to inspect Valum’s AJAX requests and responses. Look for errors in the Console or Network tabs.

  • Enable Debug Mode: Set APP_DEBUG=true in .env to get detailed error messages for failed uploads or asset loading.

  • Validate JavaScript: Ensure jQuery is loaded before Valum’s script:

    {{ asset('bundles/jquery/jquery.js') }}
    {{ asset('bundles/alvalumuploader/js/valum.js') }}
    

Tips

  1. **
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