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

时间:2022-08-29 08:06:35

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

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

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

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

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

不说废话下面分享干货


后台上传代码

<?php

namespace frontend\controllers;

use common\ToolBox\ToolExtend;
use Yii;
use yii\helpers\FileHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\imagine\Image;
use yii\web\Controller;
use yii\web\UploadedFile;

class UploadController extends Controller
{
public $enableCsrfValidation = false;//禁用Csrf验证


/**
* 上传图片到临时目录
* @return string
* @throws \yii\base\Exception
*/
public function actionImage()
{
if (Yii::$app->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, "<img src='" . $imgpath . "' class='file-preview-image' alt='" . $filename . "' title='" . $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" => "<input name='ImageFilesPath[]' id='" . $pickey . "' type='hidden' value='" . $imgpath . "'/>"
];
}
}
}

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代码

<?php

namespace common\ToolBox;

use yii;
use yii\base\Exception;

/**
* Class ToolExtend 自定义扩展类 公共方法在这里写
* @package common\ToolBox
*/
class ToolExtend
{
/**
* 生成不带横杠的UUID
* @return string
*/
public static function genuuid(){
return sprintf('%04x%04x%04x%04x%04x%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),

// 16 bits for "time_mid"
mt_rand(0, 0xffff),

// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,

// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,

// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

基于该组件重新封装

<?php
namespace common\widgets\imgupload;

use yii\base\Widget;
use yii\helpers\Html;

class ImgMultUpload extends Widget
{
//标签名称
public $label;

//初始化图片数组
public $imgarr;

//图片存储文件夹目录
public $imagedir;

private $initialPreview = [];
private $initialPreviewConfig = [];

public function init()
{
parent::init();
if ($this->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内容

<?php

use kartik\file\FileInput;
use yii\helpers\Url;

?>

<div class="form-group">
<label class="control-label col-lg-2">
<?= $label ?>
</label>

<div class="col-lg-6">
<?= FileInput::widget([
//'model' => $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("图片已经删除")
}',
]
]); ?>
</div>
</div>

在测试页面进行调用代码

<?php

/* @var $this yii\web\View */

use common\widgets\imgupload\ImgMultUpload;
use kartik\file\FileInput;
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\Url;

$this->title = 'test';

?>

<?php $form = ActiveForm::begin([
'layout' => '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' => '',
],
]
]); ?>

<?= ImgMultUpload::widget(['label' => '产品图片', 'imgarr' => [
'1987acba6a8d4ea394356080f626e1ad.jpg',
'bafc12233dc14acfb4cba448b8f0d947.jpg'
], 'imagedir' => '/uploads/temp/']); ?>
<?php
ActiveForm::end();
?>


效果如下图
yii2图片上传组件,多图上传,图片上传预览

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

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