在使用 google drive 作为应用程序的存储后端时,我们很快会遇到一个问题:google drive 使用唯一的 id 来标识每个文件和文件夹,而不是像传统文件系统那样使用直观的路径。这给集成带来了很大的麻烦,因为我们需要在应用程序中维护这些 id,并且手动进行路径转换。
例如,我们可能需要在应用程序中显示一个易于理解的路径 /My Nice Dir/myFile.ext,但在 Google Drive 中,实际的“虚拟路径”却是 /Xa3X9GlR6EmbnY1RLVTk5VUtOVkk/0B3X9GlR6EmbnY1RLVTk5VUtOVkk。手动处理这些转换不仅繁琐,而且容易出错。
masbug/flysystem-google-drive-ext 扩展包正是为了解决这个问题而生的。它是一个 Flysystem 适配器,能够无缝地在“显示路径”和“虚拟路径”之间进行转换,隐藏了 Google Drive 的内部 ID 管理,让我们可以像使用传统文件系统一样操作 Google Drive。
安装
使用 composer 安装非常简单:
composer require masbug/flysystem-google-drive-ext
配置
首先,你需要从 Google 获取 client ID、client secret 和 refresh Token。这些凭据用于授权你的应用程序访问 Google Drive。具体步骤可以参考 Google 官方文档。
获取到凭据后,就可以使用 MasbugFlysystemGoogleDriveAdapter 创建适配器实例了:
use MasbugFlysystemGoogleDriveAdapter; use GoogleClient; use GoogleServiceDrive; use LeagueFlysystemFilesystem; use LeagueFlysystemConfig; use LeagueFlysystemVisibility; $client = new Client(); $client->setClientId('[client_id]'); $client->setClientSecret('[client_secret]'); $client->refreshToken('[refresh_token]'); $client->setApplicationName('My Google Drive App'); $service = new Drive($client); // 创建适配器 $adapter = new GoogleDriveAdapter($service, 'My_App_Root'); // 创建 Flysystem 实例 $fs = new Filesystem($adapter, new Config([Config::OPTION_VISIBILITY => Visibility::PRIVATE]));
在上面的代码中,My_App_Root 指定了应用程序在 Google Drive 中使用的根目录。
使用
现在,你可以像使用任何其他 Flysystem 适配器一样使用 Google Drive 了。例如,列出根目录下的所有文件和文件夹:
$contents = $fs->listContents('', true /* is_recursive */);
上传文件:
use LeagueFlysystemLocalLocalFilesystemAdapter; use CarbonCarbon; use LeagueFlysystemUnableToWriteFile; $local_filepath = '/home/user/downloads/file_to_upload.ext'; $remote_filepath = 'MyFolder/file.ext'; $localAdapter = new LocalFilesystemAdapter('/'); $localfs = new Filesystem($localAdapter, [Config::OPTION_VISIBILITY => Visibility::PRIVATE]); try { $time = Carbon::now(); $fs->writeStream($remote_filepath, $localfs->readStream($local_filepath), new Config()); $speed = !(float)$time->diffInSeconds() ? 0 :filesize($local_filepath) / (float)$time->diffInSeconds(); echo 'Elapsed time: '.$time->diffForHumans(null, true).php_EOL; echo 'Speed: '. number_format($speed/1024,2) . ' KB/s'.PHP_EOL; } catch(UnableToWriteFile $e) { echo 'UnableToWriteFile!'.PHP_EOL.$e->getMessage(); }
下载文件:
use LeagueFlysystemLocalLocalFilesystemAdapter; use CarbonCarbon; use LeagueFlysystemUnableToWriteFile; $remote_filepath = 'MyFolder/file.ext'; $local_filepath = '/home/user/downloads/file.ext'; $localAdapter = new LocalFilesystemAdapter('/'); $localfs = new Filesystem($localAdapter, [Config::OPTION_VISIBILITY => Visibility::PRIVATE]); try { $time = Carbon::now(); $localfs->writeStream($local_filepath, $fs->readStream($remote_filepath), new Config()); $speed = !(float)$time->diffInSeconds() ? 0 :filesize($local_filepath) / (float)$time->diffInSeconds(); echo 'Elapsed time: '.$time->diffForHumans(null, true).PHP_EOL; echo 'Speed: '. number_format($speed/1024,2) . ' KB/s'.PHP_EOL; } catch(UnableToWriteFile $e) { echo 'UnableToWriteFile!'.PHP_EOL.$e->getMessage(); }
在 laravel 中使用
masbug/flysystem-google-drive-ext 也可以很方便地集成到 Laravel 框架中。
-
配置 .env 文件:
在 .env 文件中添加 Google Drive 的凭据:
FILESYSTEM_CLOUD=google GOOGLE_DRIVE_CLIENT_ID=xxx.apps.googleusercontent.com GOOGLE_DRIVE_CLIENT_SECRET=xxx GOOGLE_DRIVE_REFRESH_TOKEN=xxx GOOGLE_DRIVE_FOLDER=
-
配置 config/filesystems.php 文件:
在 config/filesystems.php 文件中添加一个名为 google 的 disk:
'disks' => [ // ... 'google' => [ 'driver' => 'google', 'clientId' => env('GOOGLE_DRIVE_CLIENT_ID'), 'clientSecret' => env('GOOGLE_DRIVE_CLIENT_SECRET'), 'refreshToken' => env('GOOGLE_DRIVE_REFRESH_TOKEN'), 'folder' => env('GOOGLE_DRIVE_FOLDER'), // without folder is root of drive or team drive ], // ... ],
-
注册 Service Provider:
在 app/Providers/AppServiceProvider.php 文件中,添加以下代码:
namespace AppProviders; use IlluminateSupportFacadesStorage; use IlluminateSupportServiceProvider; use LeagueFlysystemFilesystem; use MasbugFlysystemGoogleDriveAdapter; use GoogleClient; use GoogleServiceDrive; use IlluminateFilesystemFilesystemAdapter; class AppServiceProvider extends ServiceProvider { public function boot() { Storage::extend('google', function ($app, $config) { $client = new Client(); $client->setClientId($config['clientId']); $client->setClientSecret($config['clientSecret']); $client->refreshToken($config['refreshToken']); $service = new Drive($client); $adapter = new GoogleDriveAdapter($service, $config['folder'] ?? '/'); $driver = new Filesystem($adapter); return new FilesystemAdapter($driver, $adapter); }); } }
现在,你可以像这样访问 Google Drive:
use IlluminateSupportFacadesStorage; $googleDisk = Storage::disk('google'); // 上传文件 $googleDisk->put('MyFolder/file.ext', file_get_contents('/path/to/local/file.ext')); // 下载文件 $contents = $googleDisk->get('MyFolder/file.ext');
优势
- 无缝路径转换: 自动处理 Google Drive 的虚拟路径和显示路径之间的转换,简化了开发过程。
- 易于集成: 可以轻松地集成到现有的 Flysystem 代码中。
- 支持 Team Drive: 支持连接到 Team Drive,方便团队协作。
- 支持共享文件夹: 支持连接到与您共享的文件夹。
- 流式上传/下载: 支持直接从流中上传和下载文件,避免将数据复制到内存中,提高了性能。
局限性
- 重复文件名: Google Drive 允许用户创建具有相同显示名称的文件和文件夹。在这种情况下,适配器会选择最旧的实例。
- 并发使用: 并发使用同一个 Google Drive 可能会导致意外问题,因为文件/文件夹标识符和文件对象会被大量缓存。
总结
masbug/flysystem-google-drive-ext 扩展包是一个强大的工具,可以帮助我们更轻松地将应用程序与 Google Drive 集成。它通过无缝的路径转换,简化了文件管理,提高了开发效率。如果你正在使用 Google Drive 作为应用程序的存储后端,那么这个扩展包绝对值得一试。