解决GoogleDrive文件路径混乱问题:使用flysystem-google-drive-ext实现无缝路径转换

WBOY
发布: 2025-06-16 08:17:31
原创
125人浏览过

可以通过一下地址学习composer学习地址

在使用 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 官方文档。

获取到凭据后,就可以使用 Masbug\Flysystem\GoogleDriveAdapter 创建适配器实例了:

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]));
登录后复制

在上面的代码中,My_App_Root 指定了应用程序在 Google Drive 中使用的根目录。

使用

现在,你可以像使用任何其他 Flysystem 适配器一样使用 Google Drive 了。例如,列出根目录下的所有文件和文件夹:

$contents = $fs->listContents('', true /* is_recursive */);
登录后复制

上传文件:

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();
}
登录后复制

下载文件:

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();
}
登录后复制

在 Laravel 中使用

masbug/flysystem-google-drive-ext 也可以很方便地集成到 Laravel 框架中。

  1. 配置 .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=
    登录后复制
  2. 配置 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
        ],
        // ...
    ],
    登录后复制
  3. 注册 Service Provider:

    在 app/Providers/AppServiceProvider.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);
            });
        }
    }
    登录后复制

现在,你可以像这样访问 Google Drive:

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');
登录后复制

优势

  • 无缝路径转换: 自动处理 Google Drive 的虚拟路径和显示路径之间的转换,简化了开发过程。
  • 易于集成: 可以轻松地集成到现有的 Flysystem 代码中。
  • 支持 Team Drive: 支持连接到 Team Drive,方便团队协作。
  • 支持共享文件夹: 支持连接到与您共享的文件夹。
  • 流式上传/下载: 支持直接从流中上传和下载文件,避免将数据复制到内存中,提高了性能。

局限性

  • 重复文件名: Google Drive 允许用户创建具有相同显示名称的文件和文件夹。在这种情况下,适配器会选择最旧的实例。
  • 并发使用: 并发使用同一个 Google Drive 可能会导致意外问题,因为文件/文件夹标识符和文件对象会被大量缓存。

总结

masbug/flysystem-google-drive-ext 扩展包是一个强大的工具,可以帮助我们更轻松地将应用程序与 Google Drive 集成。它通过无缝的路径转换,简化了文件管理,提高了开发效率。如果你正在使用 Google Drive 作为应用程序的存储后端,那么这个扩展包绝对值得一试。

以上就是解决GoogleDrive文件路径混乱问题:使用flysystem-google-drive-ext实现无缝路径转换的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号