gungcahyadipp / file-service
A Laravel package for handling file operations with support for local and S3 storage
Requires
- php: ^8.0
- illuminate/contracts: ^8.0|^9.0|^10.0|^11.0
- illuminate/filesystem: ^8.0|^9.0|^10.0|^11.0
- illuminate/support: ^8.0|^9.0|^10.0|^11.0
- symfony/http-foundation: ^5.0|^6.0|^7.0
Requires (Dev)
- orchestra/testbench: ^6.0|^7.0|^8.0|^9.0
- phpunit/phpunit: ^9.0|^10.0
Suggests
- ext-imagick: Required for image compression functionality
README
A comprehensive Laravel package for handling file operations with support for both local and S3 storage, including image compression capabilities using ImageMagick.
Features
- 🗂️ Support for multiple storage disks (local, S3)
- 🖼️ Image compression with configurable quality and dimensions
- 📦 Base64 image handling
- 🏷️ Smart file naming with slug generation
- 🔄 Complete file information return (size, MIME type, URL, etc.)
- ⚙️ Configurable path structures for different storage types
- 🎯 Laravel facade support for easy usage
Requirements
- PHP >= 8.1
- Laravel >= 9.0
- ImageMagick extension (optional, for image compression)
Installation
Install the package via Composer:
composer require gungcahyadipp/file-service
Laravel Auto-Discovery
The package will automatically register its service provider and facade.
Manual Registration (if needed)
Add the service provider to your config/app.php:
'providers' => [ // ... GungCahyadiPP\FileService\Providers\FileServiceProvider::class, ],
Add the facade to your config/app.php:
'aliases' => [ // ... 'FileService' => GungCahyadiPP\FileService\Facades\FileService::class, ],
Publish Configuration
Publish the configuration file:
php artisan vendor:publish --tag=file-service-config
Configuration
The package configuration file config/file-service.php allows you to customize:
- Default storage disk
- Path structures for different disks
- Image compression settings
- File naming conventions
- Temporary directory location
Environment Variables
You can set these environment variables in your .env file:
FILE_SERVICE_DEFAULT_DISK=local FILE_SERVICE_COMPRESSION_QUALITY=70 FILE_SERVICE_MAX_WIDTH=1200 FILE_SERVICE_MAX_HEIGHT=1200
Usage
Basic File Operations
use GungCahyadiPP\FileService\Facades\FileService; // Get file URL $url = FileService::getFile('documents', 'my-file.pdf'); // Save uploaded file $fileName = FileService::saveFile($uploadedFile, 'images', 'my-image'); // Delete file $deleted = FileService::deleteFile('images', 'my-image.jpg');
Using Dependency Injection
use GungCahyadiPP\FileService\FileService; class DocumentController extends Controller { protected $fileService; public function __construct(FileService $fileService) { $this->fileService = $fileService; } public function upload(Request $request) { $file = $request->file('document'); $fileName = $this->fileService->saveFile($file, 'documents', 'my-document'); return response()->json(['filename' => $fileName]); } }
Advanced File Operations
Complete File Information
The saveFileComplete method returns comprehensive file information:
$fileInfo = FileService::saveFileComplete( $uploadedFile, 'images', 'profile-picture', true // Enable compression ); // Returns: // [ // 'title' => 'profile-picture', // 'name' => 'profile-picture-abc1.jpg', // 'path' => 'images/profile-picture-abc1.jpg', // 'size' => 1024000, // 'mime_type' => 'image/jpeg', // 'ext' => 'jpg', // 'disk' => 'local', // 'url' => 'http://localhost/storage/images/profile-picture-abc1.jpg' // ]
Base64 Image Handling
$base64Image = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIA...'; $fileName = FileService::saveBase64Image($base64Image, 'avatars', 'user-avatar'); if ($fileName) { echo "Image saved as: " . $fileName; } else { echo "Failed to save image"; }
Image Compression
Enable automatic image compression for uploaded images:
// Compress images automatically during upload $fileInfo = FileService::saveFileComplete( $uploadedFile, 'thumbnails', 'product-image', true // Enable compression );
Manual image compression:
FileService::compressImage( '/path/to/image.jpg', 85, // Quality (1-100) 800, // Max width 600 // Max height );
Storage Disk Configuration
Using Different Disks
use GungCahyadiPP\FileService\FileService; // Use specific disk $s3FileService = new FileService('s3'); $localFileService = new FileService('local'); // Save to S3 $s3FileName = $s3FileService->saveFile($file, 'documents', 'contract'); // Save to local storage $localFileName = $localFileService->saveFile($file, 'temp', 'upload');
Path Structure
The package automatically handles different path structures:
- S3:
filemanager/{folder}/{filename} - Local:
{folder}/{filename}
Error Handling
All methods include proper error handling and logging:
$fileName = FileService::saveFile($uploadedFile, 'images', 'photo'); if ($fileName) { // File saved successfully $url = FileService::getFile('images', $fileName); } else { // Handle upload failure Log::error('Failed to upload file'); }
API Reference
Methods
getFile(string $folder, string $fileName): ?string
Returns the URL of a file or null if it doesn't exist.
saveFile(UploadedFile $file, string $folder, string $fileName): string
Saves an uploaded file and returns the generated filename.
deleteFile(string $folder, string $fileName): bool
Deletes a file and returns success status.
saveBase64Image(string $base64Image, string $folder, string $fileName): string|false
Saves a Base64 encoded image and returns the filename or false on failure.
saveFileComplete(UploadedFile $file, string $folder, string $fileName, bool $is_compressed = false): array
Saves a file with complete metadata and optional compression.
deleteFileFullPath(string $path): bool
Deletes a file using its full path.
compressImage(string $pathImage, int $compressionQuality = 70, int $newMaxWidth = 1200, int $newMaxHeight = 1200): void
Compresses an image file using ImageMagick.
scaleImage(int $x, int $y, int $cx, int $cy): array
Calculates new dimensions for image scaling while maintaining aspect ratio.
Testing
composer test
Contributing
Please see CONTRIBUTING.md for details.
Security
If you discover any security-related issues, please email gungcahyadipp@gmail.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
Changelog
Please see CHANGELOG.md for details on what has changed.
Support
If you find this package useful, please consider starring it on GitHub!