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

Base64 File Bundle Laravel Package

egeloen/base64-file-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require egeloen/base64-file-bundle
    

    Add to config/bundles.php (Symfony 4+):

    return [
        // ...
        Ivory\Base64FileBundle\IvoryBase64FileBundle::class => ['all' => true],
    ];
    
  2. First Use Case Convert a base64 string to a file in your Laravel app (via Symfony's underlying framework):

    use Ivory\Base64FileBundle\Base64File;
    use Ivory\Base64FileBundle\Exception\InvalidArgumentException;
    
    $base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...';
    $file = Base64File::createFromString($base64String, 'image.png');
    $file->saveTo('/path/to/directory/image.png'); // Save to filesystem
    
  3. Key Classes

    • Base64File: Core class for handling base64 files.
    • Base64FileManager: Service for managing multiple files (if injected via Symfony DI).

Implementation Patterns

Common Workflows

1. Handling File Uploads from Base64

// In a Laravel controller (Symfony-compatible)
public function handleBase64Upload(Request $request)
{
    $base64Data = $request->input('base64_file');
    $fileName = 'upload_' . time() . '.png';

    try {
        $file = Base64File::createFromString($base64Data, $fileName);
        $file->saveTo(storage_path('app/public/uploads'));
        return response()->json(['success' => true]);
    } catch (InvalidArgumentException $e) {
        return response()->json(['error' => 'Invalid base64 data'], 400);
    }
}

2. Integration with Laravel Forms

Use with frontend frameworks (e.g., Vue/React) sending base64 data:

// Frontend (e.g., Vue)
axios.post('/upload', { base64_file: base64String });
// Laravel route
Route::post('/upload', [UploadController::class, 'handleBase64Upload']);

3. Validation

Validate base64 strings before processing:

use Ivory\Base64FileBundle\Validator\Base64FileValidator;

$validator = new Base64FileValidator();
if (!$validator->isValid($base64String)) {
    throw new \InvalidArgumentException('Invalid base64 data');
}

4. Symfony Form Integration

Extend Symfony forms to handle base64 uploads:

use Ivory\Base64FileBundle\Form\Type\Base64FileType;

$builder->add('file', Base64FileType::class, [
    'label' => 'Upload Base64 File',
    'required' => true,
]);

Laravel-Specific Tips

1. Service Provider Binding

Bind the Symfony service to Laravel's container (if needed):

// In AppServiceProvider::boot()
$this->app->singleton('ivory.base64_file.manager', function ($app) {
    return new \Ivory\Base64FileBundle\Base64FileManager();
});

2. Artisan Command for Bulk Processing

Create a custom Artisan command to process base64 files in bulk:

use Ivory\Base64FileBundle\Base64File;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ProcessBase64Command extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $base64Files = $this->getBase64FilesFromStorage();
        foreach ($base64Files as $file) {
            $base64File = Base64File::createFromString($file['data'], $file['name']);
            $base64File->saveTo(storage_path('app/processed'));
            $output->writeln("Processed: {$file['name']}");
        }
    }
}

3. File Storage Integration

Use Laravel's filesystem to handle saved files:

use Illuminate\Support\Facades\Storage;

$file->saveTo(storage_path('app/public'));
$path = Storage::disk('public')->path('image.png');

Gotchas and Tips

Pitfalls

1. Base64 Data Validation

  • Issue: The bundle does not validate MIME types or file signatures by default. Malicious or corrupted data may slip through.
  • Fix: Use Base64FileValidator or add custom validation:
    if (!preg_match('/^data:image\/(png|jpeg|gif);base64,/', $base64String)) {
        throw new \InvalidArgumentException('Unsupported MIME type');
    }
    

2. Memory Limits

  • Issue: Large base64 strings can exhaust memory during decoding.
  • Fix: Stream the file or use chunked processing:
    $file = Base64File::createFromString($base64String, 'large_file.dat', [
        'stream' => true, // Enable streaming if supported
    ]);
    

3. Symfony Dependency Conflicts

  • Issue: Laravel's autowiring may conflict with Symfony's DI container.
  • Fix: Explicitly bind services or use Laravel's make() method:
    $manager = app('ivory.base64_file.manager');
    

4. File Overwriting

  • Issue: saveTo() overwrites files by default.
  • Fix: Generate unique filenames or check existence first:
    $uniqueName = uniqid('file_', true) . '.png';
    $file->saveTo(storage_path('app/public'), $uniqueName);
    

Debugging Tips

1. Logging Errors

Enable Symfony's profiler or Laravel's logging to catch exceptions:

try {
    $file->saveTo('/path');
} catch (\Exception $e) {
    \Log::error('Base64 file error: ' . $e->getMessage());
    throw $e;
}

2. Base64 Decoding Issues

  • Symptom: InvalidArgumentException during decoding.
  • Debug: Check for:
    • Missing data: prefix (e.g., data:image/png;base64,...).
    • Invalid base64 characters (use base64_decode() to test).
    • Corrupted data (e.g., truncated strings).

3. Permission Errors

  • Symptom: Files fail to save with "Permission denied".
  • Fix: Ensure the target directory is writable:
    chmod -R 775 storage/app/public
    

Extension Points

1. Custom File Namer

Extend Base64File to auto-generate filenames:

class CustomBase64File extends Base64File
{
    public function getDefaultFilename()
    {
        return 'custom_' . parent::getDefaultFilename();
    }
}

2. Post-Processing Hooks

Add callbacks after file creation/saving:

$file = Base64File::createFromString($base64String, 'image.png');
$file->setPostSaveCallback(function ($filePath) {
    // Run additional logic (e.g., optimize image)
    exec("convert {$filePath} -quality 80 {$filePath}");
});
$file->saveTo('/path');

3. Integration with Laravel Filesystem

Create a custom filesystem adapter:

use Ivory\Base64FileBundle\Base64File;
use Illuminate\Contracts\Filesystem\Filesystem;

class Base64FilesystemAdapter implements Filesystem
{
    public function put($path, $contents, $options = [])
    {
        $file = Base64File::createFromString($contents, basename($path));
        $file->saveTo(storage_path('app'));
        return $path;
    }
    // Implement other Filesystem methods...
}

4. MIME Type Detection

Override MIME type detection for custom formats:

$file = Base64File::createFromString($base64String, 'file.txt', [
    'mimeType' => 'text/plain',
]);

Configuration Quirks

1. Default Settings

The bundle has minimal config. Override defaults via Symfony's config:

# config/packages
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.
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
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui