1. 配置
文件系统的配置在config/filesystems.php
中,各项配置可参考注释。以本地存储为例,我们重点关注disks
配置。
'disks' => ['local' => ['driver' => 'local','root' => storage_path('app'),],'public' => ['driver' => 'local','root' => storage_path('app/public'),'url' => env('APP_URL').'/storage','visibility' => 'public',]];
默认的disks.local
存储,其对应的目录是storage/app
;默认的disks.public
存储对应的目录则是app/public
。
2. 操作
我们使用Laravel内置的tinker
交互式命令行来演示,通过在项目根目录运行php artisan tin
进入交互式命令行。
>>> use Storage; // 引入Storage模块>>> $disk = Storage::disk('local'); // 获取本地存储local实例
•文件创建
>>> $disk->put('test.txt', 'this is test'); // 文件路径storage/app/test.txt
•获取文件内容
>>> $exists = $disk->exists('test.txt'); // 检查storage/app/test.txt文件是否存在>>> $file = $disk->get('test.txt'); // 读取storage/app/test.txt文件内容
•获取文件信息
>>> use Carbon\Carbon;>>> $size = $disk->size('test.txt'); // 获取storage/app/test.txt文件大小>>> $size = Storage::size('/home/test.txt'); // 这种方式要传绝对路径>>> $time = Storage::lastModified('/home/test.txt'); // 最后修改时间戳>>> $time = $disk->lastModified('test.txt');>>> $time = Carbon::createFromTimestamp($time);
•文件复制
>>> $disk->copy('test.txt', 'aa/rename.txt'); // 将storage/app/test.txt拷贝到storage/app/aa/rename.txt
•文件移动
>>> $disk->move('aa/rename.txt', 'bb/rename.txt'); // 将storage/app/aa/rename.txt移动到storage/app/bb/rename.txt
•文件复写
>>> $disk->prepend('test.txt', 'test prepend'); // 在文件开头添加>>> $disk->append('test.txt', 'test append'); // 在文件结尾添加
•文件删除
>>> $disk->delete('bb/rename.txt');>>> $disk->delete(['test1.txt', 'aa/rename.txt']); // 删除多个
•文件下载
// 在你的controller方法里return response()->download('/home/test.txt', 'rename.txt'); // 需要绝对路径, 第二个参数可指定下载后的名字return response(Storage::disk('local')->get('test.txt'), 200, ['Content-Type' => 'plain/text']); // 返回一个文件响应
•目录列表
>>> $files = $disk->files('/'); // 获取storage/app目录下全部文件>>> $allFiles = $disk->allFiles('/'); // 获取storage/app目录下全部文件(包括子目录下的文件)>>> $directories = $disk->directories('/'); // 获取storage/app目录下的所有子目录>>> $allDirectories = $disk->allDirectories('/'); // 获取storage/app目录下的所有子目录(包括子目录下的子目录)>>> $disk->makeDirectory('aa/bb'); // 在storage/app目录下创建aa/bb目录>>> $disk->deleteDirectory('aa/bb'); // 在storage/app目录下删除aa/bb目录
文章转载自私人物语,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




