laravel使用layui 上传文件 支持pdf上传

控制器:

file('file');//获取图片
        $allowed_extensions = ["png", "jpg", "gif","pdf"]; //多类型
        //图片是否是正规图片
        if ($file->getClientOriginalExtension()&&!in_array
            ($file->getClientOriginalExtension(),$allowed_extensions)) {
            $data=[
                'status'=>-1,
                'msg'=>'不支持此格式'
            ];
            return json_encode($data);
        }
        if($request->hasFile('photo')) {

        }
        //保存图片
        $path=date('Y/m/d/',time());
        $destinationPath ='uploads/blog/'.$path;
        is_dir($destinationPath) or mkdir($destinationPath,0777,true);

        $extension = $file->getClientOriginalExtension();
        $fileName = md5(str_random(10) . time()) . '.' . $extension;
        $file->move($destinationPath, $fileName);
        $data=[
            'status'=>1,
            'msg'=>$destinationPath.$fileName
        ];
        return json_encode($data);
    }
}

blade文件

...

layer js部分:

layui.use('upload', function () {
            var layer = layui.layer;
            var upload = layui.upload;
            var blogUpload = '{
    { url('url')}}'; //上传图片的路径
            //执行实例
            var uploadInst = upload.render({
                elem: '#test1' //绑定元素
                , url: blogUpload //上传接口
                ,accept: 'file'
                ,exts: 'jpg|png|gif|bmp|jpeg|pdf|docx|doc'
                ,data:{'_token':'{
    {csrf_token()}}'}
                , done: function (res) {
                    if (res.status == '1') {
                        $('#img_file').show()
                        $('#img_file').find('img').attr('src',"{
    {env('URL').'/'}}"+res.msg)  //上传成功后预览图
                        $("#fileimg").val(res.msg)
                        return layer.msg('图片上传成功!');
                    } else if (res.status == '-1') {
                        return layer.msg(res.msg);
                    } else {
                        return layer.msg('图片上传失败');
                    }
                }
                , error: function () {
                    //请求异常回调
                    return layer.msg('图片上传失败');
                }
            });
        });

你可能感兴趣的:(文件上传,js,upload,php)