File.php 10.0 KB
<?php
/**
 * +-----------------------------------------------------------------------------------------------------------------------
 * 重写 laravel-admin Form\Field\File 类
 * +-----------------------------------------------------------------------------------------------------------------------
 *
 * 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 Encore\Admin\Form\Field;
use Encore\Admin\Form\Field\File as Base;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * Class File
 *
 * @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 File 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',
    ];

    /**
     * Create a new File instance.
     *
     * @param string $column
     * @param array  $arguments
     */
    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 ($this->validator) {
            return $this->validator->call($this, $input);
        }

        /*
         * If has original value, means the form is in edit mode,
         * then remove required rule from rules.
         */
        if ($this->original()) {
            $this->removeRule('required');
        }

        /*
         * Make input data validatable if the column data is `null`.
         */
        if (Arr::has($input, $this->column) && is_null(Arr::get($input, $this->column))) {
            $input[$this->column] = '';
        }

        $rules = $attributes = [];

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

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

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

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

        $this->name = $this->getStoreName($file);

        return $this->uploadAndDeleteOriginal($file);
    }

    /**
     * Upload file and delete original file.
     *
     * @param UploadedFile $file
     *
     * @return mixed
     */
    protected function uploadAndDeleteOriginal(UploadedFile $file)
    {
        $this->renameIfExists($file);

        $path = null;

        if (!is_null($this->storagePermission)) {
            $path = $this->storage->putFileAs($this->getDirectory(), $file, $this->name, $this->storagePermission);
        } else {
            $path = $this->storage->putFileAs($this->getDirectory(), $file, $this->name);
        }

        $this->destroy();

        return $path;
    }

    /**
     * Preview html for file-upload plugin.
     *
     * @return string
     */
    protected function preview()
    {
        return $this->objectUrl($this->value);
    }

    /**
     * Initialize the caption.
     *
     * @param string $caption
     *
     * @return string
     */
    protected function initialCaption($caption)
    {
        return basename($caption);
    }

    /**
     * @return array
     */
    protected function initialPreviewConfig()
    {
        $config = ['caption' => basename($this->value), 'key' => 0];

        $config = array_merge($config, $this->guessPreviewType($this->value));

        return [$config];
    }

    /**
     * @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
        console.log("auto_upload: $auto_upload");
        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);
     var full_path = response_data.full_path;
     var original_name = response_data.original_name;

      // 设置图片的路径
    $(".file-uploading").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"));
    // 设置文件路径和件原始文件名
     $(".file-uploading").find(".kv-file-content").find("object").attr("src",full_path).attr("original_name", original_name).addClass('full-path');

//    $(".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) {

    });
});

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->options(['overwriteInitial' => true, 'msgPlaceholder' => trans('admin.choose_file')]);

        $this->setupDefaultOptions();

        if (!empty($this->value)) {
            $this->attribute('data-initial-preview', $this->preview());
            $this->attribute('data-initial-caption', $this->initialCaption($this->value));

            $this->setupPreviewOptions();
            /*
             * If has original value, means the form is in edit mode,
             * then remove required rule from rules.
             */
            unset($this->attributes['required']);
        }

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

        $this->setupScripts($options);

        return parent::render();
    }
}