laravel 上传 php 需要开启 fileinfo 扩展
先看一个例子:
$file = $request->file('shopimg'); $path = $file->store('public/avatars'); echo $path; //给storage目录public/avatars/ 上传文件 //获取文件内容 $contents = Storage::get('publicavatarsfile.jpg'); //echo $contents; //判断文件是否存在 1 $exists = Storage::disk('local')->exists('public/avatars/file.jpg'); //echo $exists;
正文:
aravel文件系统
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文件夹
1、获取上传的文件
$file=$request->file('file');
2、获取上传文件的文件名(带后缀,如abc.png)
$filename=$file->getClientOriginalName();
3、获取上传文件的后缀(如abc.png,获取到的为png)
$fileextension=$file->getClientOriginalExtension();
4、获取上传文件的大小
$filesize=$file->getClientSize();
5、获取缓存在tmp目录下的文件名(带后缀,如php8933.tmp)
$filaname=$file->getFilename();
6、获取上传的文件缓存在tmp文件夹下的绝对路径
$realpath=$file->getRealPath();
7、将缓存在tmp目录下的文件移到某个位置,返回的是这个文件移动过后的路径
$path=$file->move(path,newname);
move()方法有两个参数,第一个参数是文件移到哪个文件夹下的路径,第二个参数是将上传的文件重新命名的文件名
8、检测上传的文件是否合法,返回值为true或false
$file->isValid()
转 https://blog.csdn.net/guawawa311/article/details/83057983
https://laravelacademy.org/post/19509.html
https://www.cnblogs.com/blog-dyn/p/10310393.html