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

Aliyun Oss Storage Laravel Package

oh-my-gold/aliyun-oss-storage

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require oh-my-gold/aliyun-oss-storage
    
  2. Publish Config

    php artisan vendor:publish --provider="OhMyGold\AliyunOssStorage\AliyunOssStorageServiceProvider" --tag="config"
    

    Edit config/aliyun-oss-storage.php with your AccessKeyId, AccessKeySecret, Endpoint, and Bucket.

  3. First Use Case: Upload a File

    use OhMyGold\AliyunOssStorage\Facades\AliyunOssStorage;
    
    $path = AliyunOssStorage::putFile('folder/file.txt', storage_path('local/file.txt'));
    
  4. Verify Connection

    if (AliyunOssStorage::connected()) {
        echo "Connected to OSS!";
    }
    

Implementation Patterns

Core Workflows

  1. File Operations

    • Upload: putFile(), putObject() (for streams)
      AliyunOssStorage::putFile('path/to/file.jpg', $localPath, ['Content-Type' => 'image/jpeg']);
      
    • Download: getFile(), getObject()
      $tempPath = AliyunOssStorage::getFile('path/to/file.jpg', storage_path('temp/'));
      
    • Delete: deleteFile()
      AliyunOssStorage::deleteFile('path/to/file.jpg');
      
  2. Directory Handling

    • List Objects: listObjects() (with pagination)
      $objects = AliyunOssStorage::listObjects('folder/', ['prefix' => 'folder/']);
      
    • Create Folder: Use putObject() with a trailing / (OSS auto-creates).
  3. Metadata & Customization

    • Set metadata during upload:
      AliyunOssStorage::putFile('file.txt', $localPath, [
          'Content-Type' => 'text/plain',
          'x-oss-meta-custom' => 'value'
      ]);
      
    • Retrieve metadata:
      $metadata = AliyunOssStorage::getObjectMetadata('file.txt');
      
  4. Signed URLs (Temporary Access)

    $url = AliyunOssStorage::temporaryUrl('file.jpg', now()->addMinutes(15));
    

Integration with Laravel

  • Filesystem Integration Override Laravel’s default filesystem in config/filesystems.php:

    'oss' => [
        'driver' => 'oss',
        'key' => env('OSS_KEY'),
        'secret' => env('OSS_SECRET'),
        'endpoint' => env('OSS_ENDPOINT'),
        'bucket' => env('OSS_BUCKET'),
    ],
    

    Then use Storage::disk('oss')->put() as usual.

  • Model Storage (e.g., Images)

    use OhMyGold\AliyunOssStorage\Facades\AliyunOssStorage;
    
    public function storeImage($file) {
        $path = AliyunOssStorage::putFile(
            "users/{$this->id}/{$file->hashName()}",
            $file->path()
        );
        return $path;
    }
    
  • Queue Jobs for Async Uploads

    UploadToOss::dispatch($localPath, 'remote/path.jpg')->onQueue('oss-uploads');
    

Gotchas and Tips

Common Pitfalls

  1. Credentials Leaks

    • Never hardcode AccessKeyId/AccessKeySecret in code. Use Laravel’s .env and validate in config.
    • Restrict IAM permissions to the minimum required (e.g., avoid oss:*).
  2. Endpoint Mismatches

    • Ensure the Endpoint in config matches your OSS region (e.g., https://oss-cn-hangzhou.aliyuncs.com).
    • Test with AliyunOssStorage::connected() before production.
  3. Bucket Policy Issues

    • If uploads fail, check OSS bucket ACL (should allow public-read or your RAM role).
    • Enable CORS if uploading from a web app:
      <CORSConfiguration>
        <CORSRule>
          <AllowedOrigin>*</AllowedOrigin>
          <AllowedMethod>PUT</AllowedMethod>
        </CORSRule>
      </CORSConfiguration>
      
  4. Large File Handling

    • For files > 100MB, use multipart upload:
      $uploadId = AliyunOssStorage::initMultipartUpload('large-file.zip');
      // Upload parts...
      AliyunOssStorage::completeMultipartUpload($uploadId, ['part1', 'part2']);
      
  5. Timeouts

    • Default timeout is 5 minutes. For slow networks, increase in config:
      'timeout' => 300, // seconds
      

Debugging Tips

  • Enable Logging Add to config/aliyun-oss-storage.php:

    'debug' => env('APP_DEBUG', false),
    

    Check Laravel logs for OSS SDK errors.

  • SDK Verbose Mode Temporarily enable SDK logging:

    \OSS\OssClient::setDebug(true);
    
  • Common Errors & Fixes

    Error Cause Solution
    AccessDenied Invalid credentials Check .env and IAM permissions
    NoSuchBucket Bucket doesn’t exist Create bucket in OSS console
    InvalidArgument (Endpoint) Wrong region endpoint Use correct endpoint (e.g., cn-hangzhou)
    SlowDown Rate limiting Retry with exponential backoff

Extension Points

  1. Custom Storage Adapter Extend \OhMyGold\AliyunOssStorage\Storage\AliyunOssStorage to add:

    • Custom metadata handling.
    • Pre/post-upload hooks (e.g., thumbnail generation).
  2. Event Listeners Listen for upload/download events:

    AliyunOssStorage::addListener('uploaded', function ($event) {
        // Log or process uploaded file
    });
    
  3. Fallback to Local Storage Implement a hybrid filesystem:

    $disk = Storage::disk('oss');
    if (!$disk->exists($path)) {
        $disk = Storage::disk('local');
    }
    
  4. Testing Use a mock OSS client in tests:

    $mock = Mockery::mock('\OSS\OssClient');
    $this->app->instance('\OSS\OssClient', $mock);
    
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
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