yii2图片上传组件,多图上传,图片上传预览

参考文章  bootstrap3 文件上传插件fileinput中文说明文档

http://blog.csdn.net/lvshaorong/article/details/48730145

由于在网上搜不到相关很全的yii2上传图片组件demo,后来还是到强大的google下面找到了相关组件。

组件地址http://demos.krajee.com/widget-details/fileinput#settings

但是只有前端,后面的上传代码没有具体的示例。所以本人结合该组件写了多图上传功能。

不说废话下面分享干货


后台上传代码

request->isPost) {
            $res = [];
            $initialPreview = [];
            $initialPreviewConfig = [];
            $images = UploadedFile::getInstancesByName("ImgSelect");
            if (count($images) > 0) {
                foreach ($images as $key => $image) {
                    if ($image->size > 2048 * 1024) {
                        $res = ['error' => '图片最大不可超过2M'];
                        return json_encode($res);
                    }
                    if (!in_array(strtolower($image->extension), array('gif', 'jpg', 'jpeg', 'png'))) {
                        $res = ['error' => '请上传标准图片文件, 支持gif,jpg,png和jpeg.'];
                        return json_encode($res);
                    }
                    $dir = '/uploads/temp/';
                    //生成唯一uuid用来保存到服务器上图片名称
                    $pickey = ToolExtend::genuuid();
                    $filename = $pickey . '.' . $image->getExtension();

                    //如果文件夹不存在,则新建文件夹
                    if (!file_exists(Yii::getAlias('@frontend') . '/web' . $dir)) {
                        FileHelper::createDirectory(Yii::getAlias('@frontend') . '/web' . $dir, 777);
                    }
                    $filepath = realpath(Yii::getAlias('@frontend') . '/web' . $dir) . '/';
                    $file = $filepath . $filename;

                    if ($image->saveAs($file)) {
                        $imgpath = $dir . $filename;
                        /*Image::thumbnail($file, 100, 100)
                            ->save($file . '_100x100.jpg', ['quality' => 80]);
*/
                        array_push($initialPreview, "" . $filename . "");
                        $config = [
                            'caption' => $filename,
                            'width' => '120px',
                            'url' => '/upload/delete-pic', // server delete action
                            'key' => $pickey,
                            'extra' => ['filename' => $filename]
                        ];
                        array_push($initialPreviewConfig, $config);

                        $res = [
                            "initialPreview" => $initialPreview,
                            "initialPreviewConfig" => $initialPreviewConfig,
                            "imgfile" => ""
                        ];
                    }
                }
            }

            return json_encode($res);
        }
    }

    /**
     * 删除上传到临时目录的图片
     * @return string
     */
    public function actionDeletePic()
    {
        $error = '';
        if (Yii::$app->request->isPost) {
            $dir = '/uploads/temp/';
            $filename = yii::$app->request->post("filename");
            $filename = $dir . $filename;
            if (file_exists(Yii::getAlias('@frontend') . '/web' . $filename)) {
                unlink(Yii::getAlias('@frontend') . '/web' . $filename);
            }

            if (file_exists(Yii::getAlias('@frontend') . '/web' . $filename . '_100x100.jpg')) {
                unlink(Yii::getAlias('@frontend') . '/web' . $filename . '_100x100.jpg');
            }
        }
        return json_encode($error);
    }
}

生成唯一UUID代码


基于该组件重新封装

label === null) {
            $this->label = '上传图片';
        }

        if (is_array($this->imgarr) && count($this->imgarr) > 0) {
            foreach ($this->imgarr as $key => $value) {
                $config = ['caption' => $value,
                    'width' => '120px',
                    'url' => '/upload/delete-pic', // server delete action
                    'key' => $value,
                    'extra' => ['filename' => $value]];
                array_push($this->initialPreview, Html::img($this->imagedir . $value, [
                    'class' => 'file-preview-image',
                    'alt' => 'The Moon',
                    'title' => 'The Moon']));
                array_push($this->initialPreviewConfig, $config);
            }
        }
    }

    public function run()
    {
        return $this->render('imgfiled', [
            'label' => $this->label,
            'initialPreview' => $this->initialPreview,
            'initialPreviewConfig' => $this->initialPreviewConfig
        ]);
    }
}

views内容



$model, //'attribute' => 'ListImgUrl', 'name' => 'ImgSelect', 'language' => 'zh-CN', 'options' => ['multiple' => true, 'accept' => 'image/*'], 'pluginOptions' => [ 'initialPreview' => $initialPreview, 'initialPreviewConfig' => $initialPreviewConfig, 'allowedPreviewTypes' => ['image'], 'allowedFileExtensions' => ['jpg', 'gif', 'png'], 'previewFileType' => 'image', 'overwriteInitial' => false, 'browseLabel' => '选择图片', 'msgFilesTooMany' => "选择上传的图片数量({n}) 超过允许的最大图片数{m}!", 'maxFileCount' => 5,//允许上传最多的图片5张 'maxFileSize' => 200,//限制图片最大200kB 'uploadUrl' => Url::to(['/upload/image']), //'uploadExtraData' => ['testid' => 'listimg'], 'uploadAsync' => true,//配置异步上传还是同步上传 ], 'pluginEvents' => [ 'filepredelete' => "function(event, key) { return (!confirm('确认要删除')); }", 'fileuploaded' => 'function(event, data, previewId, index) { $(event.currentTarget.closest("form")).append(data.response.imgfile); }', 'filedeleted' => 'function(event, key) { $(event.currentTarget.closest("form")).find("#"+key).remove(); return alert("图片已经删除") }', ] ]); ?>

在测试页面进行调用代码

title = 'test';

?>

 'horizontal',
    'enableAjaxValidation' => false,
    'method' => 'post',
    'options' => ['enctype' => 'multipart/form-data'],
    'fieldConfig' => [
        'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{endWrapper}",
        'horizontalCssClasses' => [
            'label' => 'col-lg-2',
            'wrapper' => 'col-lg-6',
            'error' => 'col-lg-3',
            'hint' => '',
        ],
    ]
]); ?>

 '产品图片', 'imgarr' => [
    '1987acba6a8d4ea394356080f626e1ad.jpg',
    'bafc12233dc14acfb4cba448b8f0d947.jpg'
], 'imagedir' => '/uploads/temp/']); ?>


效果如下图
yii2图片上传组件,多图上传,图片上传预览_第1张图片

封装我只是草草封装了,有兴趣的可以重新封装。

当抛砖引玉了,有什么具体问题,欢迎在下面留言。


你可能感兴趣的:(yii2图片上传组件,多图上传,图片上传预览)