Laravel -- 文件管理及上传自定义目录及文件名

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/guawawa311/article/details/83057983

开发之路,羊肠九曲,荆棘密布,幸得高人指点,前辈填坑,一路谨小慎微,终得工程圆满;其间填坑之经验,开路之历程,皆为精华,不可弃之;记录于此,以便事后回顾,亦想于有相关开发疑惑之同学做参考之用,文中如若有错,恳请雅正,不胜感激。

Laravel文件系统

Laravel框架中对文件的管理已经很友好了,官方文档也做了很详细的说明,下面先就一些基础知识做下简单介绍,已了解的同学可以略过本部分。

系统配置

Laravel 有强大的文件系统抽象,基于Frank de Jonge 开发的PHP包,文件系统的配置文件位于 config/filesystems.php

公共磁盘

public 磁盘用于存储可以被公开访问的文件,默认情况下, public 磁盘使用 local 驱动并将文件存储在 storage/app/public ,要让这些文件可以通过web访问到,需要创建一个软链 public/storage 指向 storage/app/public ,这种方式可以将公开访问的文件保存在一个可以很容易被不同部署环境共享的目录,在使用零停机时间部署系统如Envoyer的时候尤其方便。

获取文件

get 方法用于获取指定文件
__exists__方法用于判断给定文件是否存在于磁盘上:

$contents = Storage::get('file.jpg');
$exists = Storage::disk('s3')->exists('file.jpg');

文件上传

在web应用中,最常见的存储文件案例就是存储用户上传的文件,如用户头像、照片和文档等。Laravel通过使用上传文件实例上的store方法让存储上传文件变得简单。你只需要传入上传文件保存的路径并调用store方法即可:

$path = $request->file('avatar')->store('avatars');

指定文件名

$path = $request->file('avatar')->storeAs(
    'avatars', $request->user()->id
);

文件删除

	Storage::delete(['file1.jpg', 'file2.jpg']);

自定义文件上传

使用Laravel文件上传很方便,在开发中我们需要创建软连接,但是有可能具体项目中不需要创建软连接,或者需要直接在公共盘 public 下面就能直接访问文件,这个时候就需要调整一下配置文件。

默认的驱动是__local__ 驱动 (config/filesystems.php):

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => 'your-key',
        'secret' => 'your-secret',
        'region' => 'your-region',
        'bucket' => 'your-bucket',
    ],

],

我们增加一条驱动信息:

	'root' => [
        'driver' => 'local',
        'root' => base_path(''),
    ],
    'local' => [
        'driver' => 'local',
        'root' => public_path(''),
    ],

这样该驱动指向项目根目录,然后我们在上传处理函数中:

$path = $request->file('avatar')->store(
    'public/avatars/test.png', 'root'
);

判断文件是否存在或者删除文件时:

Storage::disk('root')->delete($imagePath);

base_path 就是项目根目录
app_path 就是项目下App文件夹
storage_path 就是项目下的storage文件夹

猜你喜欢

转载自blog.csdn.net/guawawa311/article/details/83057983
今日推荐