laravel 使用常见问题记录

1、文件上传默认为storage目录,修改上传路径为public目录

if (!preg_match('/\.(jpg|jpeg|png|gif)$/', $fileName,$ext))
return response()->json(['code' => -3, 'data' => '', 'msg' => '只能上传jpg|png|gif|jpeg格式文件'])
// 移动到框架应用根目录/public/uploads/ 目录下
            $path  = $file->storeAs( date('Ymd'),uniqid().'.'.$ext[1]);
            if($path ){
                return   response()->json(['code' => 0, 'data' => ['src' =>'/uploads/'.$path], 'msg' => '']);
            }else{
                // 上传失败获取错误信息
                return    response()->json(['code' => -1, 'data' => '', 'msg' => $file->getError()]);
            }

  配置storeAs方法文件存储位置:config/filesystem.php

/*默认为local*/
 'default' => env('FILESYSTEM_DRIVER', 'local'),
/*修改public_path为默认文件上传路径*/
'disks' => [

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

2、 在控件方法中获取路由参数

     在routes/web.php设置参数

 
Route::post('{uploadfile}', 'chat\FileController@uploadImg')->where(['uploadfile'=>'^(img|file)$']);

 在自定义Controller获取路由参数

  

  //上传图片
    public function uploadImg(Request $request)
    {
      /*获取路由参数*/
       $fileType=$request->route('uploadfile');

     ............

3、部分页面取消使用token验证

    在app\Http\Middleware\VerifyCsrfToken.php 中排除指定路由

  

    /**
     * The URIs that should be excluded from CSRF verification.
     *排除upload下的所有路由使用token验证
     * @var array
     */
    protected $except = [
       '/im/service/upload/*'
    ];

  

猜你喜欢

转载自www.cnblogs.com/fogwang/p/12217253.html