Layui+PHP 文件上传

1.页面:

2.jq

//上传文件
  var uploadInst = upload.render({
    elem: '#uploadFile' //绑定元素
    ,url: '/operator/file/upload/file' //上传接口
    // ,auto: false
    ,headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
    ,accept: 'file'
    // ,bindAction: '#test9'
    ,before: function(obj) {
      this.item.siblings('#subject_file_remark').html('上传中');
      $('#subjectFile').val('');
    }
    ,done: function(res){
      if (res.code == 0)
      {
        var file_name = res.file_name;
        var url = res.url;
        $('#subjectFile').val(res.url);
        $('#subject_file_remark').html('上传成功  ' + file_name + '');
      }
      //上传完毕回调
    }
    ,error: function(){
      //请求异常回调
      $('#subject_file_remark').html('上传失败');
    }
  });

3.控制器方法:

public function postDoc(Request $request)
    {
        $data      = $request->all();
        $validator = Validator::make($data, [
            'file' => 'required|file',
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return $this->responseJSON($errors->all(), 1, 'bad request.');
        }
        
        $file = $request->file('file');
        if ($file->isValid()){
            $dir = 'files';
            $originalName = $file->getClientOriginalName(); //源文件名
            $ext = $file->getClientOriginalExtension();    //文件拓展名
            $type = $file->getClientMimeType(); //文件类型
            $realPath = $file->getRealPath();
            $disk = Storage::disk('public');
            $path = '/'.$dir.'/'.$ext;
            $disk->makeDirectory($dir);
            $file_name = date('YmdHis-').''.$originalName;
            $path = $disk->putFileAs($dir,$file,$file_name);
            return $this->responseJSON(['url' => '/storage'.'/'.$path,
                'file_name' => $file_name,
            ], 0, 'ok');
        
        }else {
            return $this->responseJSON([], 2, '文件无效');
        }
    }
    ~~~

你可能感兴趣的:(PHP,Layui,PHP,文件上传)