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

Data Uri Laravel Package

1tomany/data-uri

Parse data URIs, base64 strings, plain text, URLs, or local files into a temporary file via an immutable value object. Auto-detect or override MIME type, set an optional display name, and the temp file is deleted automatically on destruct.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require 1tomany/data-uri
    
  2. First Use Case: Decode a base64-encoded image from a data URI in a Laravel controller:

    use OneToMany\DataUri\DataDecoder;
    
    public function handleImageUpload(Request $request)
    {
        $dataUri = $request->input('image_data_uri');
        $file = DataDecoder::decode($dataUri, 'user_uploaded_image.png');
    
        // Use the file (e.g., store it, process it)
        $path = $file->getPathname();
        // File auto-deletes when $file goes out of scope
    }
    
  3. Where to Look First:

    • API Reference: Focus on DataDecoder::decode() for versatility.
    • Examples: Review decode.php for practical use cases (e.g., handling URLs, base64, and text).
    • Interface: Understand DataUriInterface methods like getPathname(), getFormat(), and getClientName().

Implementation Patterns

Core Workflows

1. Decoding Data URIs in Laravel

  • Use Case: Process user-uploaded data URIs (e.g., from rich text editors or APIs).
  • Pattern:
    $dataUri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...';
    $file = DataDecoder::decode($dataUri, 'custom_filename.png', 'image/png');
    
  • Integration:
    • Use in Form Requests or Middleware to validate/sanitize URIs before decoding.
    • Pair with Laravel’s Storage facade for persistent storage:
      Storage::put('uploads/' . $file->getClientName(), $file->getStream());
      

2. Handling Remote Files

  • Use Case: Fetch and process files from URLs (e.g., CDN assets, third-party APIs).
  • Pattern:
    $url = 'https://example.com/image.jpg';
    $file = DataDecoder::decode($url, 'remote_image.jpg');
    
  • Laravel Tip: Cache remote files using Laravel’s Cache facade to avoid repeated downloads:
    $cacheKey = 'remote_file_' . md5($url);
    $file = Cache::remember($cacheKey, now()->addHours(1), function () use ($url) {
        return DataDecoder::decode($url);
    });
    

3. Base64 and Text Data

  • Use Case: Process base64-encoded data (e.g., from APIs) or plaintext (e.g., CSV/JSON).
  • Pattern:
    // Base64
    $base64Data = 'SGVsbG8gV29ybGQ=';
    $file = DataDecoder::decodeBase64($base64Data, 'text/plain', 'greeting.txt');
    
    // Text
    $text = "Hello, world!";
    $file = DataDecoder::decodeText($text, 'message.txt');
    
  • Laravel Tip: Use decodeBase64() for API responses containing embedded assets (e.g., data:image/jpeg;base64,...):
    $apiResponse = Http::get('https://api.example.com')->json();
    $imageFile = DataDecoder::decodeBase64($apiResponse['image'], 'image/jpeg');
    

4. Temporary File Management

  • Use Case: Ensure files are cleaned up after processing (e.g., in background jobs).
  • Pattern:
    // File auto-deletes when $file is garbage collected
    $file = DataDecoder::decode($dataUri);
    // Process file...
    // No need to manually delete
    
  • Laravel Tip: For long-running processes (e.g., queues), explicitly unset the variable to trigger cleanup:
    $file = DataDecoder::decode($dataUri);
    // Process...
    unset($file); // Force cleanup
    

5. MIME Type Handling

  • Use Case: Override auto-detected MIME types (e.g., for Markdown files).
  • Pattern:
    $file = DataDecoder::decode($dataUri, null, 'text/markdown');
    
  • Laravel Tip: Use the FileType enum for common types (e.g., FileType::Json):
    use OneToMany\DataUri\FileType;
    $file = DataDecoder::decode($dataUri, null, FileType::Json);
    

Integration Tips

Laravel Filesystem

Wrap DataUriInterface in a FilesystemAdapter for seamless use with Laravel’s Storage facade:

use Illuminate\Contracts\Filesystem\FilesystemAdapter;

class DataUriAdapter implements FilesystemAdapter
{
    public function writeStream($path, $resource, $options = [])
    {
        $file = DataDecoder::decode($resource);
        return file_put_contents($path, $file->getStream());
    }
    // Implement other FilesystemAdapter methods...
}

Validation

Validate data URIs before decoding using Laravel’s Validator:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make(['data_uri' => $dataUri], [
    'data_uri' => 'required|url|mimes:data',
]);

Background Jobs

Process data URIs in queues (e.g., for async storage):

class ProcessDataUriJob implements ShouldQueue
{
    public function handle()
    {
        $file = DataDecoder::decode($this->dataUri);
        Storage::put('processed/' . $file->getClientName(), $file->getStream());
    }
}

API Responses

Return decoded files as downloads:

return response()->stream(function () use ($file) {
    echo $file->getStream();
}, 200, [
    'Content-Type' => $file->getFormat(),
    'Content-Disposition' => 'attachment; filename="' . $file->getClientName() . '"',
]);

Gotchas and Tips

Pitfalls

  1. Memory Limits:

    • Large data URIs may exceed PHP’s memory_limit. For files >10MB, consider streaming directly to disk:
      $tempPath = tempnam(sys_get_temp_dir(), 'data_uri_');
      file_put_contents($tempPath, $dataUri);
      $file = DataDecoder::decode($tempPath);
      
  2. Filename Preservation:

    • If $name is null, the package generates a random filename. Always pass a meaningful name for user-facing files:
      // Bad: Random filename
      $file = DataDecoder::decode($dataUri);
      
      // Good: Preserve original name
      $file = DataDecoder::decode($dataUri, 'user_uploaded.png');
      
  3. MIME Type Conflicts:

    • Auto-detection (via mime_content_type()) may misclassify files. Explicitly set the type for critical files:
      // Risky: Auto-detection
      $file = DataDecoder::decode($dataUri);
      
      // Safe: Explicit type
      $file = DataDecoder::decode($dataUri, null, 'application/pdf');
      
  4. Remote URL Issues:

    • The package does not validate remote URLs (e.g., HTTPS, CORS). Use Guzzle or Laravel’s Http client for pre-validation:
      $response = Http::get($url);
      $response->throw(); // Fail fast on invalid URLs
      $file = DataDecoder::decode($url);
      
  5. Garbage Collection Timing:

    • Files are deleted when the DataUriInterface object is garbage collected. For long-running scripts, manually unset the variable:
      $file = DataDecoder::decode($dataUri);
      // Process...
      unset($file); // Force cleanup
      
  6. Stream Resource Leaks:

    • Ensure streams are consumed fully before the DataUriInterface object is destroyed. Use stream_get_contents() or fpassthru():
      $stream = $file->getStream();
      $content = stream_get_contents($stream);
      fclose($stream);
      

Debugging Tips

  1. Inspect the DataUriInterface Object:

    $file = DataDecoder::decode($dataUri);
    dd([
        'path' => $file->getPathname(),
        'format' => $file->getFormat(),
        'clientName' => $file->getClientName(),
        'originalUri' => $file->getOriginalUri(), // Added in v6.0.7
    ]);
    
  2. Check for Valid Data URIs:

    • Use a regex to validate RFC 2397 compliance before decoding:
      if (!preg_match('/^data:[a-z]+\/[
      
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon