MultipleFile.php 13.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
<?php
/**
 * +-----------------------------------------------------------------------------------------------------------------------
 * 重写 laravel-admin Form\Field\MultipleFile 类
 * +-----------------------------------------------------------------------------------------------------------------------
 *
 * PHP version 7
 *
 * @category  App\Admin\Rewrite\Form\Field
 * @package   App\Admin\Rewrite\Form\Field
 * @author    Richer <yangzi1028@163.com>
 * @date      2020年11月12日13:49:31
 * @copyright 2020-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
namespace  App\Admin\Rewrite\Form\Field;

use App\Admin\Rewrite\Form\Field;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Encore\Admin\Form\Field\MultipleFile as Base;

/**
 * Class MultipleFile
 *
 * @category  App\Admin\Rewrite\Form\Field
 * @package   App\Admin\Rewrite\Form\Field
 * @author    Richer <yangzi1028@163.com>
 * @date      2020年11月12日13:49:31
 * @copyright 2020-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
class MultipleFile extends Field
{
    use UploadField;

    /**
     * Css.
     *
     * @var array
     */
    protected static $css = [
        '/vendor/laravel-admin/bootstrap-fileinput/css/fileinput.min.css?v=4.5.2',
    ];

    /**
     * Js.
     *
     * @var array
     */
    protected static $js = [
        '/vendor/laravel-admin/bootstrap-fileinput/js/plugins/canvas-to-blob.min.js',
        '/vendor/laravel-admin/bootstrap-fileinput/js/fileinput.min.js?v=4.5.2',
        '/vendor/laravel-admin/bootstrap-fileinput/js/plugins/sortable.min.js?v=4.5.2',
        '/vendor/laravel-admin/bootstrap-fileinput/js/locales/zh.js',
    ];

    /**
     * Create a new File instance.
     *
     * @param string $column
     * @param array $arguments
     * @throws \Exception
     */
    public function __construct($column, $arguments = [])
    {
        $this->initStorage();

        parent::__construct($column, $arguments);
    }

    /**
     * Default directory for file to upload.
     *
     * @return mixed
     */
    public function defaultDirectory()
    {
        return config('admin.upload.directory.file');
    }

    /**
     * {@inheritdoc}
     */
    public function getValidator(array $input)
    {
        if (request()->has(static::FILE_DELETE_FLAG)) {
            return false;
        }

        if (request()->has(static::FILE_SORT_FLAG)) {
            return false;
        }

        if ($this->validator) {
            return $this->validator->call($this, $input);
        }

        $attributes = [];

        if (!$fieldRules = $this->getRules()) {
            return false;
        }

        $attributes[$this->column] = $this->label;

        list($rules, $input) = $this->hydrateFiles(Arr::get($input, $this->column, []));

        return \validator($input, $rules, $this->getValidationMessages(), $attributes);
    }

    /**
     * Hydrate the files array.
     *
     * @param array $value
     *
     * @return array
     */
    protected function hydrateFiles(array $value)
    {
        if (empty($value)) {
            return [[$this->column => $this->getRules()], []];
        }

        $rules = $input = [];

        foreach ($value as $key => $file) {
            $rules[$this->column.$key] = $this->getRules();
            $input[$this->column.$key] = $file;
        }

        return [$rules, $input];
    }

    /**
     * Sort files.
     *
     * @param string $order
     *
     * @return array
     */
    protected function sortFiles($order)
    {
        $order = explode(',', $order);

        $new = [];
        $original = $this->original();

        foreach ($order as $item) {
            $new[] = Arr::get($original, $item);
        }

        return $new;
    }

    /**
     * Prepare for saving.
     *
     * @param UploadedFile|array $files
     *
     * @return mixed|string
     */
    public function prepare($files)
    {
        if (request()->has(static::FILE_DELETE_FLAG)) {
            return $this->destroy(request(static::FILE_DELETE_FLAG));
        }

        if (is_string($files) && request()->has(static::FILE_SORT_FLAG)) {
            return $this->sortFiles($files);
        }

        $targets = array_map([$this, 'prepareForeach'], $files);

        return array_merge($this->original(), $targets);
    }

    /**
     * @return array|mixed
     */
    public function original()
    {
        if (empty($this->original)) {
            return [];
        }

        return $this->original;
    }

    /**
     * Prepare for each file.
     *
     * @param UploadedFile $file
     *
     * @return mixed|string
     */
    protected function prepareForeach(UploadedFile $file = null)
    {
        $this->name = $this->getStoreName($file);

        return tap($this->upload($file), function () {
            $this->name = null;
        });
    }

    /**
     * Preview html for file-upload plugin.
     *
     * @return array
     */
    protected function preview()
    {
        $files = $this->value ?: [];

        return array_values(array_map([$this, 'objectUrl'], $files));
    }

    /**
     * Initialize the caption.
     *
     * @param array $caption
     *
     * @return string
     */
    protected function initialCaption($caption)
    {
        if (empty($caption)) {
            return '';
        }

        $caption = array_map('basename', $caption);

        return implode(',', $caption);
    }

    /**
     * @return array
     */
    protected function initialPreviewConfig()
    {
        $files = $this->value ?: [];

        $config = [];

        foreach ($files as $index => $file) {
            $preview = array_merge([
                'caption' => basename($file),
                'key'     => $index,
            ], $this->guessPreviewType($file));

            $config[] = $preview;
        }

        return $config;
    }

    /**
     * Allow to sort files.
     *
     * @return $this
     */
    public function sortable()
    {
        $this->fileActionSettings['showDrag'] = true;

        return $this;
    }

    /**
     * add by Richer 于 2020年6月3日10:13:15 增加方法,设置上传的路径
     *
     * 设置上传的url
     */
    protected function setUploadUrl()
    {
        return '/service/qiniu-upload?filetype=all&is_original_name=1';
    }

    /**
     * @param string $options
     */
    protected function setupScripts($options)
    {
        // add by Richer 是否自动上传
        $auto_upload = Arr::get(obj_2_array(json_decode($options)), 'auto_upload', 0);
        $this->script = <<<EOT
$("input{$this->getElementClassSelector()}").fileinput({$options});
EOT;

        if ($this->fileActionSettings['showRemove']) {
            $text = [
                'title'   => trans('admin.delete_confirm'),
                'confirm' => trans('admin.confirm'),
                'cancel'  => trans('admin.cancel'),
            ];

            $this->script .= <<<EOT
$("input{$this->getElementClassSelector()}").on('filebeforedelete', function() {

    return new Promise(function(resolve, reject) {

        var remove = resolve;

        swal({
            title: "{$text['title']}",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "{$text['confirm']}",
            showLoaderOnConfirm: true,
            cancelButtonText: "{$text['cancel']}",
            preConfirm: function() {
                return new Promise(function(resolve) {
                    resolve(remove());
                });
            }
        });
    });
})
 // 选择文件后处理事件
.on("filebatchselected", function(e, files) {
    // TODO
    if ($(".kv-fileinput-error.file-error-message").is(":hidden")){
        // 清除当前的预览图 ,并隐藏 【移除】 按钮
        // $(this).fileinput('clear').fileinput('unlock')
        // 文件选择完直接调用上传方法。
        // TODO
        if ($auto_upload==1) {
            $(this).fileinput("upload");
        }
    }
})
// 上传前
.on('filepreupload', function(event, data, previewId, index) {
    $(this).fileinput('clear').fileinput('unlock')
})
// 异步上传成功结果处理
.on('fileuploaded', function(event, data, previewId, index) {
//    console.log("异步");
    // 上传成功后的样式 file-preview-success
    var obj = $(".file-preview-success").eq(index);
    // 设置图片的路径
    obj.find(".kv-file-content").find("img").attr("src",data.response.data[0].full_path);
})
//异步上传失败结果处理
.on('fileerror', function (event, data, msg) {
   // console.log(event, data, msg);
   //alert(msg)
})
//异步上传失败结果处理
.on('fileuploaderror', function (event, data, msg) {
    //console.log(msg);
   // console.log(event, data, msg);
   //alert(msg);
//   if (msg != '无效的文件上传.') {
//      //  swal_error(msg)
//        $(".kv-fileinput-error.file-error-message").find("li").text(msg);
//   }
//
   //
})
.on('filebatchuploaderror', function(event, data, msg) {
       // alert();
})
// 同步上传回调
.on('filebatchuploadsuccess', function(event,data,previewId,index) {
//    console.log(event);
//    console.log(data);
//    console.log(previewId);
//    console.log(index);
//    console.log($(".file-preview-frame"));
//    console.log($(".file-preview-success"));
    var response_data = data.response.data;
//    console.log(response_data);
//    $(".file-preview-frame.krajee-default.kv-preview-thumb").each(function (i,e) {
//       // console.log(response_data[i].full_path);
//        //console.log( $(this).parent().html());
//    });

    // 上传成功后的样式 file-preview-success
    $("div[id^='uploaded-']").each(function (i,e) {

    });
    // 设置路径
    $(".file-uploading").each(function (i,e) {
        var full_path = response_data[i].full_path;
        var original_name = response_data[i].original_name;
//        console.log(full_path);
//        console.log(original_name);
        // kv-preview-data file-preview-object file-object type-default
        // 设置图片的路径
        $(this).find(".kv-file-content").find("img").attr("src",full_path).attr("original_name", original_name).addClass('full-path');
//         console.log( $(this).find(".kv-file-content").find("object"));
        // 设置文件路径和件原始文件名
         $(this).find(".kv-file-content").find("object").attr("src",full_path).attr("original_name", original_name).addClass('full-path');


        // 设置图片的可以移动
        $(this).addClass("file-sortable");
//        var html = '<span class="drag-handle-init text-info" title="移动 / 重置"&gt;<i class="glyphicon glyphicon-move"&gt;</i&gt;</span&gt;';
//
//         $(this).find(".file-thumbnail-footer").prepend(html);

        var span = document.createElement("span");  //创建元素
        span.className = 'file-drag-handle11';
        span.className += ' drag-handle-init';
        span.className += ' text-info';
        span.style.float = 'left';
        span.style.cursor = 'move;';
        span.style.margin = '5px 0 -40px';
        span.style.width = '16px';
        span.style.height = '16px';
        span.style.cursor = 'move';
        span.style.opacity = '1';
        span.title="移动 / 重置";
        var i = document.createElement("i");  //创建元素
        i.className = 'glyphicon';
        i.className += ' glyphicon-move';
        span.appendChild(i);
        //console.log(span);
        //$(this).find(".file-thumbnail-footer").prepend(span);
        $(this).find(".file-thumbnail-footer").find(".file-actions").after(span);
//        $(this).find(".file-thumbnail-footer").find(".file-actions").after(html);
//        //console.log( $(this).find(".file-thumbnail-footer").html());
    });
});

EOT;
        }

        if ($this->fileActionSettings['showDrag']) {
            $this->addVariables([
                'sortable'  => true,
                'sort_flag' => static::FILE_SORT_FLAG,
            ]);

            $this->script .= <<<EOT
$("input{$this->getElementClassSelector()}").on('filesorted', function(event, params) {

    var order = [];

    params.stack.forEach(function (item) {
        order.push(item.key);
    });

    $("input{$this->getElementClassSelector()}_sort").val(order);
});
EOT;
        }
    }

    /**
     * Render file upload field.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function render()
    {
        $this->attribute('multiple', true);

        $this->setupDefaultOptions();

        if (!empty($this->value)) {
            $this->options(['initialPreview' => $this->preview()]);
            $this->setupPreviewOptions();
        }
        // add By Richer 于 2019年7月16日18:07:35
        if ($this->fileActionSettings['showRemove'] && !Arr::get($this->options, 'deleteUrl')) {
            $deleteUrl = str_replace('/edit', '', request()->url());

            $this->options['deleteUrl'] = $deleteUrl;
        }

        $options = json_encode($this->options);

        $this->setupScripts($options);

        return parent::render();
    }

    /**
     * Destroy original files.
     *
     * @param string $key
     *
     * @return array.
     */
    public function destroy($key)
    {
        $files = $this->original ?: [];

        $file = Arr::get($files, $key);

        if (!$this->retainable && $this->storage->exists($file)) {
            $this->storage->delete($file);
        }

        unset($files[$key]);

        return $files;
    }
}