Yii2.0 using Plupload to implement multi-graph upload _php instance with zoom function

Source: Internet
Author: User
Tags file upload getmessage learn php yii

This article explained the code of Plupload, realized the Ajax multiple map upload at the same time, and then zoom the picture, and finally show the picture, share for everyone to reference, the specific content as follows

1, the article View call Plupload

<?= \common\widgets\plupload::widget ([
 ' model ' => $model,
 ' attribute ' => ' cover_img ',
 ' url ' = > '/file/upload ',//Processing file Upload Controller
]?>

2, \common\widgets\plupload components

<?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 parameter cannot be null ');
  } if (! $this->model) {throw new Exception (' model property cannot be empty ');
  } if (! $this->attribute) {throw new Exception (' attribute property cannot be null ');
  The public Function run () {$model = $this->model;
  $attribute = $this->attribute; $path = $model-> $attribute? $model-> $attribute: "/images/noimage.gif";//show article picture or default picture $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; "
  ></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
Register Related 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 Processing Code

function Initcoverimageuploader (buttonid,contatinerid,maxfilesize,url,csrftoken) {var uploader = new Plupload. Uploader ({runtimes: ' Html5,flash,silverlight,html4 ', Browse_button:buttonid,//can pass a ID ... container: Contatinerid,//... or DOM Element itself url:url, Flash_swf_url: ' @vendor/moxiecode/plupload/js/moxie.swf ', sil Verlight_xap_url: ' @vendor/moxiecode/plupload//js/moxie.xap ', filters: {max_file_size:maxfilesize, Mime_type S: [{title: "Image Files", Extensions: "Jpg,gif,png"}, {title: "Zip Files", Extensions: "Zip"}]}, mu
   ltipart_params:{' _csrf ': Csrftoken}, init: {filesadded:function (up, files) {Uploader.start ();
   }, Uploadprogress:function (up, file) {$ (' # ' +contatinerid+ ' P '). Text (' uploaded: ' +file.percent+ ');
    }, Fileuploaded:function (up, file, result) {result = $.parsejson (result.response); if (Result.code = = 0) {$ (' # ' +buttonid). html ('  

5, Backend\assets\pluploadasset
Register Plupload Related Resources

<?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
the controller invokes the model to process the upload file and returns the result

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 ()];}}



The

7, Common\models\imageupload
Model detects uploaded files, and then scales the source files in a certain scale

<?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 ';//upload Form file name public $savePath;//Image Save root location  Public $allowExt = [' jpg ', ' png ', ' jpeg ', ' gif ', ' BMP '];//allow upload suffix public $maxFileSize =1024100000;//maximum size 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;//upload file private $filePath;//file path private $urlPath//access path private $res =false;//return status private $messag
 e;//returns the information public function GetMessage () {return $this->message;
 The Public Function Geturlpath () {return $this->urlpath;

  The Public Function init () {if (! $this->fileinputname) throw new Exception (' fileinputname attribute cannot be empty '); 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 = ' no permissions created '. $this->savepath;
   return false;
  }} $this->_uploadfile = Uploadedfile::getinstancebyname ($this->fileinputname);
   if (! $this->_uploadfile) {$this->message = ' No upload file found ';
  return false;
   } if ($this->_uploadfile->error) {$this->message = ' upload failed ';
  return false; } if (!in_array ($this->extension, $this->allowext) | |!in_array ($this->type, $this->allowtype)) {$this-&
   Gt;message = ' This file type is not allowed to upload ';
  return false;
   } if ($this->_uploadfile->size> $this->maxfilesize) {$this->message = ' file too large ';
  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; The Public Function Save () {if ($this->_uploadfile->saveas ($this->filepath)) {$this->createthumbnail ($this
  ->filepath)//Zoom picture $this->res = true;
  }else{$this->res = false; } if ($this->res) {$this->message = $this->_uploadfile->basename. '. '
  $this->_uploadfile->extension. ' Upload success '; }else{$this->message = $this->_uploadfile->basename.
  $this->_uploadfile->extension. ' Upload failed ';
 return $this->res; /** * Get file name * @return NULL */Public Function getbasename () {if ($this->_uploadfile) {return $this->
  _uploadfile->basename;
  }else{return null;
}/** * Returns the file suffix * @return null/Public Function getextension () {if ($this->_uploadfile) {   return $this->_uploadfile->extension;
  }else{return null; /** * Returns the file type * @return Mixed/Public Function GetType () {if ($this->_uploadfile) {return $this->_
  uploadfile->type;
 return null; /** * Generates thumbnails that maintain the aspect ratio of the original image, supports the. png. jpg. gif * Thumbnail type is unified in the. png format * $toFile thumbnail file name, empty overwrite the original image file * $to W thumbnail width * $toH thumbnail height * @return bool/public static function Createthumbnail ($srcFile, $toFile = "", $toW =100, $to

  H=100) {if ($toFile = = "") $toFile = $srcFile;
  $data = getimagesize ($srcFile);//return array containing 4 cells, 0-wide, 1-high, 2-image type, 3-wide text description.
  if (! $data) return false; Load the file into the resource variable im switch ($data [2])//1-gif,2-jpg,3-png {case 1:if (!function_exists ("Imagecreatefromgif")) Retu
    RN 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
  ///compute the width and height of the thumbnail $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);//Create a new True color image if ($ni) {
   Resampling copies of part of the image and resizing it to maintain better sharpness imagecopyresampled ($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
    else {//Copy part of the image and resize $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;
 }
}

The above is the entire content of this article, I hope that you learn PHP program help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.