EasyAdmin增加上传文件组件属性

增加效果前
在这里插入图片描述
增加效果后
在这里插入图片描述
修改文件位置
\public\static\plugs\easy-admin\easy-admin.js

  upload: function () {
                var uploadList = document.querySelectorAll("[data-upload]");
                var uploadSelectList = document.querySelectorAll("[data-upload-select]");
				

                if (uploadList.length > 0) {
                    $.each(uploadList, function (i, v) {
                        var uploadExts = $(this).attr('data-upload-exts') || init.upload_exts,
                            uploadName = $(this).attr('data-upload'),
                            uploadNumber = $(this).attr('data-upload-number') || 'one',
                            uploadSign = $(this).attr('data-upload-sign') || '|',
                            uploadAccept = $(this).attr('data-upload-accept') || 'file',
                            uploadAcceptMime = $(this).attr('data-upload-mimetype') || '',
							uploadviewtype = $(this).attr('data-upload-viewtype') || '',//我添加的,默认保存id,显示文件名和连接"选项list"
                            elem = "input[name='" + uploadName + "']",  
                            uploadElem = this;
                            
                        // 监听上传事件
                        upload.render({
                            elem: this,
                            url: admin.url(init.upload_url),
                            exts: uploadExts,
                            accept: uploadAccept,//指定允许上传时校验的文件类型
                            acceptMime: uploadAcceptMime,//规定打开文件选择框时,筛选出的文件类型
                            multiple: uploadNumber !== 'one',//是否多文件上传
                            headers:admin.headers(),
                            done: function (res) {
								//console.log(res);
                                if (res.code === 1) {
                                    var url =null;
										  switch (uploadviewtype) {
								      case "list":url =res.data.id;// 
                                                  break;							  
								      default:
									       url =res.data.url;
									  }
             									
                                    if (uploadNumber !== 'one') {
                                      var oldUrl = $(elem).val();//viewtype=list时此值为ID
									  switch (uploadviewtype) {
								      case "list":if (oldUrl !== '') { 
                                                url = oldUrl + uploadSign + url; 
                                                } 
                                                break;							  
								      default:
									       if (oldUrl !== '') {
                                                url = oldUrl + uploadSign + url;
                                              }
									  }
									 
                                       
                                    }
                                    $(elem).val(url);
									$(elem).trigger("input");
                                    admin.msg.success(res.msg);
                                } else {
                                    admin.msg.error(res.msg);
                                }
                                return false;
                            }
                        });

                        // 监听上传input值变化
                        $(elem).bind("input propertychange", function (event) {
                            var urlString = $(this).val(), 
                                urlArray = urlString.split(uploadSign),
                                uploadIcon = $(uploadElem).attr('data-upload-icon') || "file";

                            $('#' + uploadName).remove();
                            if (urlString.length > 0) {
                                var parant = $(this).parent('div');
                                var liHtml = '';
                              //  $.each(urlArray, function (i, v) {
                              //      liHtml += '<li><a><img src="' + v + '" data-image  onerror="this.src=\'' + BASE_URL + 'admin/images/upload-icons/' + uploadIcon + '.png\';this.onerror=null"></a><small class="uploads-delete-tip bg-red badge" data-upload-delete="' + uploadName + '" data-upload-url="' + v + '" data-upload-sign="' + uploadSign + '">×</small></li>\n';
                              //  });
							  switch (uploadviewtype) {
								  case "list": $.ajaxSettings.async = false;
				                                        $.getJSON(admin.url("ajax/getfilesinfo?ids="+urlString), function (data) {
                                                        if (data.msg== "ok") {  
				                                         	 $.each(data.data, function (i, v) {
																  
                                               liHtml += '<li><a href="'+v.url+';this.onerror=null"">'+v.original_name+'</a><small class="uploads-delete-tip bg-red badge" data-upload-delete="' + uploadName + '" data-upload-url="' + v.id + '" data-upload-sign="' + uploadSign + '">×</small></li>\n';
                                                });
                                                              }  
				                                         });
								              
								              break;
									 default:  $.each(urlArray, function (i, v) {
										 
                                               liHtml += '<li><a><img src="' + v + '" data-image  onerror="this.src=\'' + BASE_URL + 'admin/images/upload-icons/' + uploadIcon + '.png\';this.onerror=null"></a><small class="uploads-delete-tip bg-red badge" data-upload-delete="' + uploadName + '" data-upload-url="' + v + '" data-upload-sign="' + uploadSign + '">×</small></li>\n';
                                                });
								  
							     } 
                                parant.after('<ul id="' + uploadName + '" class="layui-input-block layuimini-upload-show">\n' + liHtml + '</ul>');
                            }

                        });

                        // 非空初始化图片显示
                        if ($(elem).val() !== '') {
                            $(elem).trigger("input");
                        }
                    });

                    // 监听上传文件的删除事件
                    $('body').on('click', '[data-upload-delete]', function () {
                        var uploadName = $(this).attr('data-upload-delete'),
                            deleteUrl = $(this).attr('data-upload-url'),
                            sign = $(this).attr('data-upload-sign');
                        var confirm = admin.msg.confirm('确定删除?', function () {
                            var elem = "input[name='" + uploadName + "']";
                            var currentUrl = $(elem).val();
                            var url = '';
                            if (currentUrl !== deleteUrl) {
                                url = currentUrl.search(deleteUrl) === 0 ? currentUrl.replace(deleteUrl + sign, '') : currentUrl.replace(sign + deleteUrl, '');
                                $(elem).val(url);
                                $(elem).trigger("input");
                            } else {
                                $(elem).val(url);
                                $('#bing-' + uploadName).remove();
                            }
                            admin.msg.close(confirm);
                        });
                        return false;
                    });
                }

                if (uploadSelectList.length > 0) {
                    $.each(uploadSelectList, function (i, v) {
                        var uploadName = $(this).attr('data-upload-select'),
                            uploadNumber = $(this).attr('data-upload-number') || 'one',
                            uploadSign = $(this).attr('data-upload-sign') || '|';

                        var selectCheck = uploadNumber === 'one' ? 'radio' : 'checkbox';
                        var elem = "input[name='" + uploadName + "']",
                            uploadElem = $(this).attr('id');

                        tableSelect.render({
                            elem: "#" + uploadElem,
                            checkedKey: 'id',
                            searchType: 'more',
                            searchList: [
                                {searchKey: 'title', searchPlaceholder: '请输入文件名'},
                            ],
                            table: {
                                url: admin.url('ajax/getUploadFiles'),
                                cols: [[
                                    {type: selectCheck},
                                    {field: 'id', title: 'ID'},
                                    {field: 'url', minWidth: 80, search: false, title: '图片信息', imageHeight: 40, align: "center", templet: admin.table.image},
                                    {field: 'original_name', width: 150, title: '文件原名', align: "center"},
                                    {field: 'mime_type', width: 120, title: 'mime类型', align: "center"},
                                    {field: 'create_time', width: 200, title: '创建时间', align: "center", search: 'range'},
                                ]]
                            },
                            done: function (e, data) {
                                var urlArray = [];
                                $.each(data.data, function (index, val) {
                                    urlArray.push(val.url)
                                });
                                var url = urlArray.join(uploadSign);
                                admin.msg.success('选择成功', function () {
                                    $(elem).val(url);
                                    $(elem).trigger("input");
                                });
                            }
                        })

                    });

                }
            },

\vendor\zhongshaofa\easy-admin\src\upload\trigger\SaveDb.php

   public static function trigger($tableName, $data)
    {
        if (isset($data['original_name'])) {
            $data['original_name'] = htmlspecialchars($data['original_name'], ENT_QUOTES);
        }
      return  Db::name($tableName)->insertGetId($data);//我修改的
    }

\vendor\zhongshaofa\easy-admin\src\upload\driver\Local.php

 public function save()
    {
        parent::save();
        $savedb=SaveDb::trigger($this->tableName, [
            'upload_type'   => $this->uploadType,
            'original_name' => $this->file->getOriginalName(),
            'mime_type'     => $this->file->getOriginalMime(),
            'file_ext'      => strtolower($this->file->getOriginalExtension()),
            'url'           => $this->completeFileUrl,
			'admin_id'           =>session("admin.id"),
			'user_id'           => session("admin.user_id"),
            'create_time'   => time(),
        ]);
        return [
            'save' => true,
            'msg'  => '上传成功',
            'url'  => $this->completeFileUrl,
			'original_name' => $this->file->getOriginalName(),
			'id'=>$savedb
        ];
    }

\app\admin\controller\Ajax.php

  public function upload()
    {
        $this->checkPostRequest();
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('file'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            $this->success($upload['msg'], ['url' => $upload['url'],'id'=>$upload['id'],'filename'=>$upload['original_name']]);
        } else {
            $this->error($upload['msg']);
        }
    }

通过以上修改增加返回了文件的id,及原文件名

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值