yii2.0使用Plupload實(shí)現(xiàn)帶縮放功能的多圖上傳
本文講解了plupload的相關(guān)代碼,實(shí)現(xiàn)了ajax多圖同時上傳,然后將圖片進(jìn)行縮放,最后顯示圖片,分享給大家供大家參考,具體內(nèi)容如下
1、文章視圖中調(diào)用Plupload
<?= \common\widgets\Plupload::widget([ 'model'=>$model, 'attribute'=>'cover_img', 'url'=>'/file/upload',//處理文件上傳控制器 ])?>
2、\common\widgets\Plupload 組件
<?php
namespace common\widgets;
use backend\assets\UploadAsset;
use yii;
use yii\helpers\Html;
use yii\base\Exception;
class Plupload extends yii\bootstrap\Widget{
public $model;
public $attribute;
public $name;
public $url;
private $_html;
public function init(){
parent::init();
if(!$this->url){
throw new Exception('url參數(shù)不能為空');
}
if(!$this->model){
throw new Exception('model屬性不能為空');
}
if(!$this->attribute){
throw new Exception('attribute屬性不能為空');
}
}
public function run(){
$model = $this->model;
$attribute = $this->attribute;
$path = $model->$attribute?$model->$attribute:"/images/noimage.gif";//顯示文章圖片或者默認(rèn)圖片
$this->_html.='<div class="form-group field-article-author" id="container">';
$this->_html.=Html::activeLabel($model,$attribute);
$this->_html.=Html::activeHiddenInput($model,$attribute,['id'=>'hidden_input','value'=>$path]);
$this->_html .= '<div id="pickfiles" style="height:50px;min-width:50px;max-width: 300px;overflow: hidden;"><img height="50" src="'.$path.'" /></div>';
$this->_html.='</div> ';
UploadAsset::register($this->view);
$this->view->registerJs(
'$(function(){
initCoverImageUploader("pickfiles","container","2mb","'.$this->url.'","'.Yii::$app->request->getCsrfToken().'");
});'
);
return $this->_html;
}
}
3、backend\assets\UploadAsset
注冊相關(guān)js
<?php
namespace backend\assets;
use yii\web\AssetBundle;
class UploadAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
];
public $js = [
'js/upload.js'
];
public $depends = [
'backend\assets\PluploadAsset',
];
}
4、js/upload.js
ajax處理代碼
function initCoverImageUploader(buttonId,contatinerId,maxFileSize,url,csrfToken){
var uploader = new plupload.Uploader({
runtimes : 'html5,flash,silverlight,html4',
browse_button :buttonId, // you can pass an id...
container: contatinerId, // ... or DOM Element itself
url : url,
flash_swf_url : '@vendor/moxiecode/plupload/js/Moxie.swf',
silverlight_xap_url : '@vendor/moxiecode/plupload//js/Moxie.xap',
filters : {
max_file_size : maxFileSize,
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
]
},
multipart_params:{
'_csrf':csrfToken
},
init: {
FilesAdded: function(up, files) {
uploader.start();
},
UploadProgress: function(up, file) {
$('#'+contatinerId+' p').text('已上傳:'+file.percent+'%');
},
FileUploaded:function (up, file, result) {
result = $.parseJSON(result.response);
if(result.code == 0){
$('#'+buttonId).html('<img src="'+result.path+'" height="50" />');
$('#hidden_input').val(result.path);
//console.log(result.message);
}
},
Error: function(up, err) {
document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
}
}
});
uploader.init();
}
5、backend\assets\PluploadAsset
注冊plupload相關(guān)資源
<?php
namespace backend\assets;
use yii\web\AssetBundle;
class PluploadAsset extends AssetBundle
{
public $sourcePath = '@vendor/moxiecode/plupload';
public $css = [
];
public $js = [
'js/plupload.full.min.js',
];
public $depends = [
'yii\web\JqueryAsset',
];
}
6、FileController
控制器調(diào)用模型處理上傳文件,并且返回結(jié)果
class FileController extends BaseController
{
public function actionUpload(){
Yii::$app->response->format=Response::FORMAT_JSON;
$model = New ImageUpload();
$model->fileInputName = 'file';
if($model->save()){
return ['code'=>0,'message'=>$model->getMessage(),'path'=>$model->getUrlPath()];
}else{
return ['code'=>1,'message'=>$model->getMessage()];
}
}
}
7、common\models\ImageUpload
模型中對上傳文件做了一定的檢測,然后將源文件按照一定的比例進(jìn)行縮放
<?php
namespace common\models;
use yii\base\Exception;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;
class ImageUpload extends \yii\base\Object
{
public $fileInputName = 'file';//上傳表單 file name
public $savePath ;//圖像保存根位置
public $allowExt = ['jpg','png','jpeg','gif','bmp'];//允許上傳后綴
public $maxFileSize=1024100000;//最大大小
public $allowType = ['image/jpeg','image/bmp','image/gif','image/png','image/pjpeg','image/bmp','image/gif','image/x-png','image/pjpeg','image/bmp', 'image/gif' ,'image/x-png','image/pjpeg','image/bmp','image/gif','image/x-png'];
private $_uploadFile;//上傳文件
private $filePath;//文件路徑
private $urlPath;//訪問路徑
private $res=false;//返回狀態(tài)
private $message;//返回信息
public function getMessage(){
return $this->message;
}
public function getUrlPath(){
return $this->urlPath;
}
public function init(){
if(!$this->fileInputName) throw new Exception('fileInputName屬性不能為空');
if(!$this->savePath) $this->savePath = \Yii::$app->basePath.'/web/uploads/images';
$this->savePath = rtrim($this->savePath,'/');
if(!file_exists($this->savePath)){
if(! FileHelper::createDirectory($this->savePath)){
$this->message = '沒有權(quán)限創(chuàng)建'.$this->savePath;
return false;
}
}
$this->_uploadFile = UploadedFile::getInstanceByName($this->fileInputName);
if(!$this->_uploadFile){
$this->message = '沒有找到上傳文件';
return false;
}
if($this->_uploadFile->error){
$this->message = '上傳失敗';
return false;
}
if(!in_array($this->extension,$this->allowExt) || !in_array($this->type,$this->allowType)){
$this->message = '該文件類型不允許上傳';
return false;
}
if($this->_uploadFile->size> $this->maxFileSize){
$this->message = '文件過大';
return false;
}
$path = date('Y-m',time());
if(!file_exists($this->savePath.'/'.$path)){
FileHelper::createDirectory($this->savePath.'/'.$path);
}
$name = substr(\Yii::$app->security->generateRandomString(),-4,4);
$this->filePath = $this->savePath.'/'.$path.'/'.$this->baseName.'--'.$name.'.'.$this->extension;
$this->urlPath = '/uploads/images/'.$path.'/'.$this->baseName.'--'.$name.'.'.$this->extension;
}
public function save(){
if($this->_uploadFile->saveAs($this->filePath)){
$this->CreateThumbnail($this->filePath);//縮放圖片
$this->res = true;
}else{
$this->res = false;
}
if($this->res){
$this->message = $this->_uploadFile->baseName.'.'.$this->_uploadFile->extension.'上傳成功';
}else{
$this->message = $this->_uploadFile->baseName.'.'.$this->_uploadFile->extension.'上傳失敗';
}
return $this->res;
}
/**
* 獲取文件名字
* @return null
*/
public function getBaseName(){
if($this->_uploadFile){
return $this->_uploadFile->baseName;
}else{
return null;
}
}
/**
* 返回文件后綴
* @return null
*/
public function getExtension(){
if($this->_uploadFile){
return $this->_uploadFile->extension;
}else{
return null;
}
}
/**
* 返回文件類型
* @return mixed
*/
public function getType(){
if($this->_uploadFile){
return $this->_uploadFile->type;
}
return null;
}
/**
* 生成保持原圖縱橫比的縮略圖,支持.png .jpg .gif
* 縮略圖類型統(tǒng)一為.png格式
* $srcFile 原圖像文件名稱
* $toFile 縮略圖文件名稱,為空覆蓋原圖像文件
* $toW 縮略圖寬
* $toH 縮略圖高
* @return bool
*/
public static function CreateThumbnail($srcFile, $toFile="", $toW=100, $toH=100)
{
if ($toFile == "") $toFile = $srcFile;
$data = getimagesize($srcFile);//返回含有4個單元的數(shù)組,0-寬,1-高,2-圖像類型,3-寬高的文本描述。
if (!$data) return false;
//將文件載入到資源變量im中
switch ($data[2]) //1-GIF,2-JPG,3-PNG
{
case 1:
if(!function_exists("imagecreatefromgif")) return false;
$im = imagecreatefromgif($srcFile);
break;
case 2:
if(!function_exists("imagecreatefromjpeg")) return false;
$im = imagecreatefromjpeg($srcFile);
break;
case 3:
if(!function_exists("imagecreatefrompng")) return false;
$im = imagecreatefrompng($srcFile);
break;
}
//計算縮略圖的寬高
$srcW = imagesx($im);
$srcH = imagesy($im);
$toWH = $toW / $toH;
$srcWH = $srcW / $srcH;
if ($toWH <= $srcWH) {
$ftoW = $toW;
$ftoH = (int)($ftoW * ($srcH / $srcW));
} else {
$ftoH = $toH;
$ftoW = (int)($ftoH * ($srcW / $srcH));
}
if (function_exists("imagecreatetruecolor")) {
$ni = imagecreatetruecolor($ftoW, $ftoH); //新建一個真彩色圖像
if ($ni) {
//重采樣拷貝部分圖像并調(diào)整大小 可保持較好的清晰度
imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
} else {
//拷貝部分圖像并調(diào)整大小
$ni = imagecreate($ftoW, $ftoH);
imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
}
} else {
$ni = imagecreate($ftoW, $ftoH);
imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
}
switch ($data[2]) //1-GIF,2-JPG,3-PNG
{
case 1:
imagegif($ni, $toFile);
break;
case 2:
imagejpeg($ni, $toFile);
break;
case 3:
imagepng($ni, $toFile);
break;
}
ImageDestroy($ni);
ImageDestroy($im);
return $toFile;
}
}
以上就是本文的全部內(nèi)容,希望對大家學(xué)習(xí)php程序設(shè)計有所幫助。
- 基于ThinkPHP5.0實(shí)現(xiàn)圖片上傳插件
- thinkphp實(shí)現(xiàn)圖片上傳功能分享
- ThinkPHP文件上傳實(shí)例教程
- ThinkPHP結(jié)合AjaxFileUploader實(shí)現(xiàn)無刷新文件上傳的方法
- Thinkphp多文件上傳實(shí)現(xiàn)方法
- thinkPHP3.2簡單實(shí)現(xiàn)文件上傳的方法
- 封裝ThinkPHP的一個文件上傳方法實(shí)例
- thinkphp jquery實(shí)現(xiàn)圖片上傳和預(yù)覽效果
- PHP + plupload.js實(shí)現(xiàn)多圖上傳并顯示進(jìn)度條加刪除實(shí)例代碼
- 使用JS+plupload直接批量上傳圖片到又拍云
- thinkPHP5框架整合plupload實(shí)現(xiàn)圖片批量上傳功能的方法
相關(guān)文章
PHP接口類(interface)的定義、特點(diǎn)和應(yīng)用示例
這篇文章主要介紹了PHP接口類(interface),結(jié)合實(shí)例形式分析了PHP接口類(interface)的基本功能、定義、特點(diǎn)、用法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2020-05-05
淺析Yii2 GridView 日期格式化并實(shí)現(xiàn)日期可搜索教程
這篇文章主要介紹了Yii2 GridView 日期格式化并實(shí)現(xiàn)日期可搜索教程的相關(guān)資料,需要的朋友可以參考下2016-04-04
基于PHP Web開發(fā)MVC框架的Smarty使用說明
本篇文章小編為大家介紹,基于PHP Web開發(fā)MVC框架的Smarty使用說明。需要的朋友參考下2013-04-04
實(shí)例(Smarty+FCKeditor新聞系統(tǒng))
實(shí)例(Smarty+FCKeditor新聞系統(tǒng))...2007-01-01
PHP 5.6.11 訪問SQL Server2008R2的幾種情況詳解
這篇文章主要介紹了PHP 5.6.11 訪問SQL Server2008R2的幾種情況的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08
PHP設(shè)計模式之觀察者模式(Observer)詳細(xì)介紹和代碼實(shí)例
這篇文章主要介紹了PHP設(shè)計模式之觀察者模式(Observer)詳細(xì)介紹和代碼實(shí)例,需要的朋友可以參考下2014-04-04

