PHP code example of watsonhaw / think-filesystem

1. Go to this page and download the library: Download watsonhaw/think-filesystem library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

watsonhaw / think-filesystem example snippets


return [
    // 默认磁盘
    'default' => env('filesystem.driver', 'local'),
    // 磁盘列表
    'disks'   => [
        'local'  => [
            'type' => 'local',
            'root'   => app()->getRuntimePath() . 'storage',
        ],
        'public' => [
            // 磁盘类型
            'type'       => 'local',
            // 磁盘路径
            'root'       => app()->getRootPath() . 'public/storage',
            // 磁盘路径对应的外部URL路径
            'url'        => '/storage',
            // 可见性
            'visibility' => 'public',
        ],
        // 更多的磁盘配置信息
    ],
];

return [
    // 默认磁盘
    'default' => env('filesystem.driver', 'aliyun'),
    // 磁盘列表
    'disks'   => [
        'aliyun' => [
            'type' => 'aliyun',
            'access_id' => '******',
            'access_secret' => '******',
            'bucket' => 'bucket',
            'endpoint' => 'oss-cn-hongkong.aliyuncs.com',
            'isCName' => true,
            'cdnUrl' => '',
            'prefix' => '',
            'options' => [
                'endpoint' => '',
                'bucket_endpoint' => '',
            ],
        ],
        'qcloud' => [
            'type' => 'qcloud',
            'region' => '***', //bucket 所属区域 英文
            'app_id' => '***', // 域名中数字部分
            'secret_id' => '***',
            'secret_key' => '***',
            'bucket' => '***',
            'timeout' => 60,
            'connect_timeout' => 60,
            'cdn' => '您的 CDN 域名',
            'scheme' => 'https',
            'read_from_cdn' => false,
        ]
    ],
];

$file = $this->request->file('image');
try {
    validate(
        [
            'image' => [
                // 限制文件大小(单位 byte),这里限制为 4MB
                'fileSize' => 4 * 1024 * 1024,
                // 限制文件后缀,多个后缀以英文逗号分割
                'fileExt'  => 'gif,jpg,png,jpeg',
            ],
        ]
    )->check(['image' => $file]);

    $path = \watsonhaw\filesystem\facade\Filesystem::disk('public')->putFile('test', $file);
    $url  = \watsonhaw\filesystem\facade\Filesystem::disk('public')->url($path);

    return json(['path' => $path, 'url' => $url]);
} catch (\think\exception\ValidateException $e) {
    echo $e->getMessage();
}

use watsonhaw\filesystem\facade\Filesystem;

// 使用默认的 local 磁盘
Filesystem::disk('local')->put('example.txt', 'Hello, think-filesystem!');
echo Filesystem::disk('local')->get('example.txt');

// 使用 public 磁盘(需要在配置中定义)
$path = Filesystem::disk('public')->putFile('images', $file);
// 获取文件的可访问 URL
$url = Filesystem::disk('public')->url($path); // /storage/images/xxx.jpg

// 获取文件的绝对路径
$absolutePath = Filesystem::disk('local')->path('example.txt');

// 设置文件可见性
Filesystem::disk('public')->setVisibility('secret.txt', 'private');
echo Filesystem::disk('public')->getVisibility('secret.txt'); // private

// 目录操作
Filesystem::disk('local')->makeDirectory('docs');
$files = Filesystem::disk('local')->files('docs');
$dirs = Filesystem::disk('local')->directories('docs');

$contents = Filesystem::get('file.jpg');

if (Filesystem::disk('local')->exists('file.jpg')) {
    // ...
}

if (Filesystem::disk('local')->missing('file.jpg')) {
    // ...
}

return Filesystem::download('file.jpg');

return Filesystem::download('file.jpg', $name, $headers);

$url = Filesystem::url('file.jpg');

use watsonhaw\filesystem\facade\Filesystem;

// ============ 阿里云 OSS 图片处理 ============
// 文档:https://help.aliyun.com/zh/oss/user-guide/img-parameters

// 方式一:字符串形式,按 OSS 文档拼接好即可
$thumb = Filesystem::disk('aliyun')->url('images/a.jpg', [
    'url_params' => 'x-oss-process=image/resize,m_fill,w_200,h_200/format,webp/quality,80',
]);

// 方式二:key=>value 形式,url_params 会被自动作为 query 追加
$thumb = Filesystem::disk('aliyun')->url('images/a.jpg', [
    'url_params' => [
        'x-oss-process' => 'image/resize,m_fill,w_200,h_200/format,webp',
    ],
]);

// ============ 腾讯云 COS 图片处理 ============
// 文档:https://cloud.tencent.com/document/product/436/44870

// COS 图片处理参数的 key 本身包含斜杠(如 imageMogr2/thumbnail/200x200!),无对应 value
// 推荐使用「数字索引数组」形式传入原始字符串,框架不会对它做任何编码
$thumb = Filesystem::disk('qcloud')->url('images/a.jpg', [
    'url_params' => [
        'imageMogr2/thumbnail/200x200!/format/webp/quality/80',
    ],
]);

// 等价写法:使用空值 key => '' 形式
$thumb = Filesystem::disk('qcloud')->url('images/a.jpg', [
    'url_params' => ['imageMogr2/thumbnail/200x200!/format/webp/quality/80' => ''],
]);

use watsonhaw\filesystem\facade\Filesystem;

// 生成 1 小时内有效的临时访问 URL
$url = Filesystem::disk('aliyun')->temporaryUrl('private/report.pdf', 3600);

$url = Filesystem::disk('qcloud')->temporaryUrl('private/report.pdf', 3600);

// OSS 私有 Bucket:x-oss-process 会自动参与签名,访问时不会 403
$thumb = Filesystem::disk('aliyun')->temporaryUrl('images/a.jpg', 3600, [
    'url_params' => ['x-oss-process' => 'image/resize,w_200,h_200/format,webp'],
]);

// COS 私有 Bucket:imageMogr2 参数会自动参与签名
$thumb = Filesystem::disk('qcloud')->temporaryUrl('images/a.jpg', 3600, [
    'url_params' => ['imageMogr2/thumbnail/200x200!/format/webp'],
]);

$size = Filesystem::size('file.jpg');

$time = Filesystem::lastModified('file.jpg');

$mime = Filesystem::mimeType('file.jpg')

$path = Filesystem::path('file.jpg');

Filesystem::put('file.jpg', $contents);

Filesystem::put('file.jpg', $resource);

if (! Filesystem::put('file.jpg', $contents)) {
    // 该文件无法写入磁盘...
}

'public' => [
    'type' => 'local',
    // ...
    'throw' => true,
],

Filesystem::prepend('file.log', 'Prepended Text');

Filesystem::append('file.log', 'Appended Text');

Filesystem::copy('old/file.jpg', 'new/file.jpg');

Filesystem::move('old/file.jpg', 'new/file.jpg');

use think\File;

// 为文件名自动生成一个唯一的 ID...
$path = Filesystem::putFile('photos', new File('/path/to/photo'));

// 手动指定一个文件名...
$path = Filesystem::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');

use think\File;

// putFile 参数顺序:目录, 上传文件, 文件名规则(null=自动生成唯一ID), 选项数组
$path = Filesystem::putFile(
    'photos',
    new File('/path/to/photo'),
    null,
    ['visibility' => 'public']
);

Filesystem::delete('file.jpg');

Filesystem::delete(['file.jpg', 'file2.jpg']);

Filesystem::disk('aliyun')->delete('path/file.jpg');

$files = Filesystem::files($directory);
$files = Filesystem::allFiles($directory);

$directories = Filesystem::directories($directory);
$directories = Filesystem::allDirectories($directory);

Filesystem::makeDirectory($directory);

Filesystem::deleteDirectory($directory);

use League\Flysystem\Filesystem as FlysystemFilesystem;
use think\App;
use think\Service;
use watsonhaw\filesystem\facade\Filesystem;

// 示例:接入一个自定义驱动(以假设的 ftp 适配器为例,实际需自行安装对应 flysystem 适配器包并保证与 league/flysystem 3.x 兼容)
// use League\Flysystem\Ftp\FtpAdapter;
// use League\Flysystem\Ftp\FtpConnectionOptions;

class AppService extends Service
{
    public function boot()
    {
        Filesystem::extend('ftp', function (App $app, array $config) {
            // $adapter = new FtpAdapter(FtpConnectionOptions::fromArray($config));
            // 闭包必须返回 League\Flysystem\Filesystem 实例
            return new FlysystemFilesystem($adapter, $config);
        });
    }
}