在使用 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 安装非常简单:
<code>composer require masbug/flysystem-google-drive-ext</code>
配置
首先,你需要从 Google 获取 client ID、client secret 和 refresh token。这些凭据用于授权你的应用程序访问 Google Drive。具体步骤可以参考 Google 官方文档。
获取到凭据后,就可以使用 Masbug\Flysystem\GoogleDriveAdapter 创建适配器实例了:
<code class="php">use Masbug\Flysystem\GoogleDriveAdapter;
use Google\Client;
use Google\Service\Drive;
use League\Flysystem\Filesystem;
use League\Flysystem\Config;
use League\Flysystem\Visibility;
$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]));</code>在上面的代码中,My_App_Root 指定了应用程序在 Google Drive 中使用的根目录。
使用
现在,你可以像使用任何其他 Flysystem 适配器一样使用 Google Drive 了。例如,列出根目录下的所有文件和文件夹:
<code class="php">$contents = $fs->listContents('', true /* is_recursive */);</code>上传文件:
<code class="php">use League\Flysystem\Local\LocalFilesystemAdapter;
use Carbon\Carbon;
use League\Flysystem\UnableToWriteFile;
$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();
}</code>下载文件:
<code class="php">use League\Flysystem\Local\LocalFilesystemAdapter;
use Carbon\Carbon;
use League\Flysystem\UnableToWriteFile;
$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();
}</code>在 Laravel 中使用
masbug/flysystem-google-drive-ext 也可以很方便地集成到 Laravel 框架中。
配置 .env 文件:
在 .env 文件中添加 Google Drive 的凭据:
<code>FILESYSTEM_CLOUD=google GOOGLE_DRIVE_CLIENT_ID=xxx.apps.googleusercontent.com GOOGLE_DRIVE_CLIENT_SECRET=xxx GOOGLE_DRIVE_REFRESH_TOKEN=xxx GOOGLE_DRIVE_FOLDER=</code>
配置 config/filesystems.php 文件:
在 config/filesystems.php 文件中添加一个名为 google 的 disk:
<code class="php">'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
],
// ...
],</code>注册 Service Provider:
在 app/Providers/AppServiceProvider.php 文件中,添加以下代码:
<code class="php">namespace App\Providers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use Masbug\Flysystem\GoogleDriveAdapter;
use Google\Client;
use Google\Service\Drive;
use Illuminate\Filesystem\FilesystemAdapter;
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);
});
}
}</code>现在,你可以像这样访问 Google Drive:
<code class="php">use Illuminate\Support\Facades\Storage;
$googleDisk = Storage::disk('google');
// 上传文件
$googleDisk->put('MyFolder/file.ext', file_get_contents('/path/to/local/file.ext'));
// 下载文件
$contents = $googleDisk->get('MyFolder/file.ext');</code>优势
局限性
总结
masbug/flysystem-google-drive-ext 扩展包是一个强大的工具,可以帮助我们更轻松地将应用程序与 Google Drive 集成。它通过无缝的路径转换,简化了文件管理,提高了开发效率。如果你正在使用 Google Drive 作为应用程序的存储后端,那么这个扩展包绝对值得一试。
以上就是解决GoogleDrive文件路径混乱问题:使用flysystem-google-drive-ext实现无缝路径转换的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号