laravel 多图上传及图片的存储

1.了解文件磁盘配置:

'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

在filesystems.php文件中创建了一个名为 public的文件磁盘,使用的驱动为本地存储,'root’表示的是文件最终存储的目标路径是storage/app/public, ‘url’ 表示的是文件的url,'visibility’表示的是可见性
2.创建软连接,在项目的根目录运行如下命令:

php artisan storage:link

如果是线上代码,则需要在服务器中的项目根目录运行。
软连接的创建意味着项目的 …/public/storage/ 路径直接指向了 …/storage/app/public/ 目录
3.接收图片并存储,返回存储的图片的url

class UploadController extends Controller
{
    public function upload()
    {
        $imgs = [];
        if (request()->hasFile('file')){
            foreach (request()->file('file') as $file){
            //将图片存储到了 ../storage/app/public/product/ 路径下
                $path = $file->store('public/product');
                $path = str_replace('public','',$path);
                $imgs[]= asset('storage/'.$path);
            }
             return response()->json([
                    'errno'=>0,
                    'data'=>$imgs
                ]);
        }else{
            return response()->json([
                'info'=>'没有图片'
            ]);
        }
        //处理多图上传并返回数组
    }
}

猜你喜欢

转载自blog.csdn.net/qq_20933903/article/details/83023736