Laravel5.1 框架文件管理操作实例分析(2)
2 获取硬盘实例
要进行文件管理需要那到硬盘实例,我们可以通过 Storage 门面的 disk 方法来获取,之后就可以进行我们想要的操作了:
public function index()
{
$disk = Storage::disk('local');
// 创建一个文件
$disk->put('file1.txt', 'Laravel Storage');
}
3 文件操作
3.1 获取文件
public function index()
{
// 取到磁盘实例
$disk = Storage::disk('local');
// 取出文件
$file = $disk->get('test.txt');
dd($file);
}
我们可以使用get()方法获取到文件 以字符串的形式传入文件名就行,但是需要主意:如果你要取到子目录以下的文件时需要传入路径,比如:$disk->get('subpath/.../.../.../file.txt');
3.2 判断文件是否存在
public function index()
{
// 取到磁盘实例
$disk = Storage::disk('local');
// 取出文件
$exists = $disk->exists('image.png');
dd($exists); // false
}
3.3 获取文件信息
文件大小:
public function index()
{
// 取到磁盘实例
$disk = Storage::disk('local');
// 取出文件
$size = Storage::size('/home/test.txt');
dd($size); // 4
}
最后修改时间:
public function index()
{
// 取到磁盘实例
$disk = Storage::disk('local');
// 取出文件
$time = Storage::lastModified('file1.txt'); // 1507701271
$time = Carbon::createFromTimestamp($time);
echo $time; // 2017-10-11 05:54:31
}
3.4 储存文件
public function index()
{
// 取到磁盘实例
$disk = Storage::disk('local');
// 储存文件
$disk->put('file2.txt', 'file2 content'); // 新建一个文件
}
3.5 Copy文件
public function index()
{
// 取到磁盘实例
$disk = Storage::disk('local');
// 拷贝文件 第一个参数是要拷贝的文件,第二个参数是拷贝到哪里
$disk->copy('home/test.txt','rename.txt');
}
3.6 移动文件
public function index()
{
// 取到磁盘实例
$disk = Storage::disk('local');
// 拷贝文件 第一个参数是要移动的文件,第二个参数是移动到哪里
$disk->move('file2.txt', 'home/file.txt');
}
3.7 在文件开头/结尾添加内容
public function index()
{
// 取到磁盘实例
$disk = Storage::disk('local');
// 在文件开头添加
$disk->prepend('file1.txt', 'test prepend');
// 在文件末尾添加
$disk->append('file1.txt', 'test append');
}
内容版权声明:除非注明,否则皆为本站原创文章。
