Browse Source

feat: 增加upload小部件以及对upload action的优化

wechat_public_accounts
iron 5 years ago
parent
commit
982b958a7d
  1. 1
      common/models/Category.php
  2. 30
      kcadmin/controllers/CategoryController.php
  3. 8
      kcadmin/views/category/_form.php
  4. 98
      kcadmin/views/category/test.php
  5. 81
      vendor/iron/actions/UploadAction.php
  6. 146
      vendor/iron/assets/upload/css/jquery-file-upload.css
  7. 148
      vendor/iron/assets/upload/css/jquery-file-upload.min.css
  8. 936
      vendor/iron/assets/upload/js/jquery-file-upload.js
  9. 1
      vendor/iron/assets/upload/js/jquery-file-upload.min.js
  10. 5
      vendor/iron/assets/upload/js/jquery.min.js
  11. 46
      vendor/iron/web/UploadAsset.php
  12. 2
      vendor/iron/widgets/Excel.php
  13. 215
      vendor/iron/widgets/Upload.php

1
common/models/Category.php

@ -2,6 +2,7 @@
namespace common\models;
use iron\wegets\Upload;
use Yii;
use yii\behaviors\TimestampBehavior;

30
kcadmin/controllers/CategoryController.php

@ -10,6 +10,7 @@ use yii\helpers\Html;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
/**
* CategoryController implements the CRUD actions for Category model.
@ -36,12 +37,26 @@ class CategoryController extends Controller
public function actions()
{
return [
'test' => [
'upload' => [
'class' => 'iron\actions\UploadAction',
'path' => 'xls/'
]
];
}
public function actionSaveDatabase()
{
Yii::$app->response->format = Response::FORMAT_JSON;
//TODO save data in database
return ['status'=>true];
}
public function actionPreviews()
{
Yii::$app->response->format = Response::FORMAT_JSON;
return [['name' => '111', 'path' => '/uploads/15736315233032.jpg', 'size' => 1024]];
}
/**
* @author iron
* 文件导出
@ -55,7 +70,7 @@ class CategoryController extends Controller
} else {
$dataProvider = $searchModel->search($params);
}
\iron\widget\Excel::export([
\iron\widgets\Excel::export([
'models' => $dataProvider->getModels(),
'format' => 'Xlsx',
'asAttachment' => true,
@ -64,6 +79,11 @@ class CategoryController extends Controller
]);
}
public function actionTest()
{
return $this->renderPartial('test');
}
/**
* Lists all Category models.
* @return mixed
@ -79,6 +99,12 @@ class CategoryController extends Controller
]);
}
public function actionImageDel()
{
Yii::$app->response->format = Response::FORMAT_JSON;
return ['status' => true];
}
/**
* Displays a single Category model.
* @param integer $id

8
kcadmin/views/category/_form.php

@ -21,11 +21,15 @@ use blobt\widgets\Icheck;
<?php //$form->field($model, 'icon_type')->widget(Select2::className(), ["items" => $model::$iconType, "promptText" => false]) ?>
<?= $form->field($model, 'icon_type')->widget(Icheck::className(), ["items" => $model::$iconType,'type' => "radio"]) ?>
<?= $form->field($model, 'icon_type')->widget(Icheck::className(), ["items" => $model::$iconType, 'type' => "radio"]) ?>
<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'sort_order')->textInput() ?>
<?= $form->field($model, 'sort_order')->widget(\iron\widgets\Upload::className(), [
'url' => 'upload',
'deleteUrl' => 'imageDel',
'dragdropWidth'=> 800
]) ?>
<?= $form->field($model, 'created_at')->widget(DatetimePicker::className()) ?>

98
kcadmin/views/category/test.php

@ -0,0 +1,98 @@
<?php
/*
* The MIT License
*
* Copyright 2019 Blobt.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
?>
<header>
<link href="http://hayageek.github.io/jQuery-Upload-File/4.0.11/uploadfile.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/4.0.11/jquery.uploadfile.min.js"></script>
</header>
<body>
<div id="showoldupload">
<div class="ajax-upload-dragdrop" style="vertical-align: top; width: 600px;">
<div class="ajax-file-upload" style="position: relative; overflow: hidden; cursor: default;">Upload
<form method="POST" action="upload.php" enctype="multipart/form-data" style="margin: 0px; padding: 0px;">
<input type="file" id="ajax-upload-id-1573635462220" name="myfile[]" accept="*" multiple=""
style="position: absolute; cursor: pointer; top: 0px; width: 100%; height: 100%; left: 0px; z-index: 100; opacity: 0;">
</form>
</div>
<span><b>Drag &amp; Drop Files</b></span></div>
<div></div>
</div>
<div class="ajax-file-upload-container"></div>
</body>
<script>
$("#showoldupload").uploadFile(
{
url: "upload",
dragDrop: true,
fileName: "file",
returnType: "json",
showDelete: true,
showDownload: false,
statusBarWidth: 300,
dragdropWidth: 300,
maxFileSize: 200 * 1024,
dragDropStr: "<span><b>拖动上传</b></span>",
sizeErrorStr: "图片超过最大尺寸限制",
uploadErrorStr: "上传失败",
showPreview: true,
previewHeight: "60px",
previewWidth: "60px",
onSuccess: function (files, data) {
$.ajax({
url: "save-database",
dataType: "json",
data: {data: data, fileName: files},
});
},
onLoad: function (obj) {
$.ajax({
cache: false,
url: "previews",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.length; i++) {
obj.createProgress(data[i]["name"], data[i]["path"], data[i]["size"]);
}
}
});
},
deleteCallback: function (data, pd) {
for (var i = 0; i < data.length; i++) {
// alertify.confirm('系统提示', "确定执行批量 '"+act+"' 操作?", function() {
$.post("image-del", {op: "delete", name: data[i]},
function (resp, textStatus, jqXHR) {
//Show Message
alert("File Deleted");
});
// },function(){
// });
}
pd.statusbar.hide(); //You choice.
},
});
</script>

81
vendor/iron/actions/UploadAction.php

@ -28,7 +28,9 @@ namespace iron\actions;
use yii\base\Action;
use Yii;
use yii\base\Exception;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\web\ServerErrorHttpException;
use yii\web\UploadedFile;
/***
@ -45,7 +47,11 @@ class UploadAction extends Action
* 常量: 二进制数据类型
*/
const DATA_TYPE_BINARY = 2;
/**
* @var function
*
*/
public $saveInDatabase;
/**
* @var integer 限制的最大尺寸
*/
@ -56,6 +62,7 @@ class UploadAction extends Action
public $allowType;
/**
* @var string 文件保存路径
* template /image/jpg/
*/
public $path;
/**
@ -91,30 +98,40 @@ class UploadAction extends Action
{
Yii::$app->response->format = Response::FORMAT_JSON;
$data = [];
d(Yii::$app->request->post());exit;
if ($this->dataType == self::DATA_TYPE_FORM) {
$files = UploadedFile::getInstancesByName('files');
} else {
//TODO 非表单类型的文件上传
$files = [];
}
try {
foreach ($files as $file) {
if ($this->dataType == self::DATA_TYPE_FORM) {
$file = UploadedFile::getInstanceByName('file');
$this->checkType($file->extension);
$this->checkSize($file->size);
$savePath = $this->getSavePath();
$fileName = $this->getFileName($file->baseName);
$filePath = "$savePath/$fileName.{$file->extension}";
$filePath = "$savePath$fileName.{$file->extension}";
$file->saveAs($filePath);
$data[] = ["uploads/$this->path/$fileName.{$file->extension}"];
// $data[] = ["uploads/$this->path/$fileName.{$file->extension}"];
} else {
//TODO 非表单类型的文件上传
throw new NotFoundHttpException('未实现');
// $bin = Yii::$app->request->post('file');
// $head = substr($bin, 0, 2);
// $fileExtension = $this->getExtension($head);
// $fileName = $this->getFileName();
// $savePath = $this->getSavePath();
// $filePath = "$savePath/$fileName.{$fileExtension}";
// file_put_contents($filePath, $bin);
}
return ['status' => true, 'paths' => $data];
} catch (\Exception $e) {
return ['status' => false, 'info' => $e->getMessage()];
return ['status' => true, 'path' => "uploads/$this->path$fileName.{$file->extension}"];
} catch (\Error $e) {
throw new ServerErrorHttpException($e->getMessage());
// return ['status' => false, 'info' => $e->getMessage()];
}
}
protected function saveData()
{
}
/**
* 检查文件类型是否允许上传
* @param $extension 文件扩展名
@ -138,11 +155,35 @@ class UploadAction extends Action
*/
protected function checkSize($size)
{
if ($size/1024 > $this->maxSize) {
if ($size / 1024 > $this->maxSize) {
throw new Exception("文件大于允许的最大尺寸【{$this->maxSize}】,请修改配置或压缩文件");
}
}
/**
* 根据二进制流头大小判断文件类型
* @param $head
* @return mixed
* @throws NotFoundHttpException
*/
protected function getExtension($head)
{
$fileTypes = array(
7790 => 'exe',
7784 => 'midi',
8297 => 'rar',
255216 => 'jpg',
7173 => 'gif',
6677 => 'bmp',
13780 => 'png'
);
if (isset($fileTypes[$head])) {
return $fileTypes[$head];
} else {
throw new NotFoundHttpException('未找到该文件类型');
}
}
/**
* 获取文件保存路径并创建文件夹
* @return string 文件保存的完成路径
@ -150,14 +191,14 @@ class UploadAction extends Action
protected function getSavePath()
{
$dirs = explode('/', $this->path);
$savePath = Yii::getAlias('@app').'/web/uploads';
$savePath = Yii::getAlias('@app') . '/web/uploads';
if (!is_dir($savePath)) {
mkdir($savePath, 755);
mkdir($savePath, 0755);
}
foreach ($dirs as $dir) {
$savePath .= "/{$dir}";
$savePath .= "/$dir";
if (!is_dir($savePath)) {
mkdir($savePath, 755);
mkdir($savePath, 0755);
}
}
return $savePath;
@ -169,7 +210,7 @@ class UploadAction extends Action
* @return string
*/
//TODO 利用原文件名生成新文件名
protected function getFileName($originName)
protected function getFileName($originName = '')
{
return time() . rand(0, 9999);
}

146
vendor/iron/assets/upload/css/jquery-file-upload.css

@ -0,0 +1,146 @@
.ajax-file-upload-statusbar {
border: 1px solid #0ba1b5;
margin-top: 10px;
width: 420px;
margin-right: 10px;
margin: 5px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
padding: 5px 5px 5px 15px
}
.ajax-file-upload-filename {
width: 300px;
height: auto;
margin: 0 5px 5px 0px;
}
.ajax-file-upload-filesize {
width: 50px;
height: auto;
margin: 0 5px 5px 0px;
display: inline-block;
vertical-align:middle;
}
.ajax-file-upload-progress {
margin: 5px 10px 5px 0px;
position: relative;
width: 250px;
border: 1px solid #ddd;
padding: 1px;
border-radius: 3px;
display: inline-block;
color:#FFFFFF;
}
.ajax-file-upload-bar {
background-color: #0ba1b5;
width: 0;
height: 20px;
border-radius: 3px;
color:#FFFFFF;
}
.ajax-file-upload-percent {
position: absolute;
display: inline-block;
top: 3px;
left: 48%
}
.ajax-file-upload-red {
-moz-box-shadow: inset 0 39px 0 -24px #e67a73;
-webkit-box-shadow: inset 0 39px 0 -24px #e67a73;
box-shadow: inset 0 39px 0 -24px #e67a73;
background-color: #e4685d;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
display: inline-block;
color: #fff;
font-family: arial;
font-size: 13px;
font-weight: normal;
padding: 4px 15px;
text-decoration: none;
text-shadow: 0 1px 0 #b23e35;
cursor: pointer;
vertical-align: top;
margin: 5px 10px 5px 0px;
}
.ajax-file-upload-green {
background-color: #77b55a;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
margin: 0;
padding: 0;
display: inline-block;
color: #fff;
font-family: arial;
font-size: 13px;
font-weight: normal;
padding: 4px 15px;
text-decoration: none;
cursor: pointer;
text-shadow: 0 1px 0 #5b8a3c;
vertical-align: top;
margin: 5px 10px 5px 0px;
}
.ajax-file-upload {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
font-weight: bold;
padding: 15px 20px;
cursor:pointer;
line-height:20px;
height:25px;
margin:0 10px 10px 0;
display: inline-block;
background: #fff;
border: 1px solid #e8e8e8;
color: #888;
text-decoration: none;
border-radius: 3px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
-moz-box-shadow: 0 2px 0 0 #e8e8e8;
-webkit-box-shadow: 0 2px 0 0 #e8e8e8;
box-shadow: 0 2px 0 0 #e8e8e8;
padding: 6px 10px 4px 10px;
color: #fff;
background: #2f8ab9;
border: none;
-moz-box-shadow: 0 2px 0 0 #13648d;
-webkit-box-shadow: 0 2px 0 0 #13648d;
box-shadow: 0 2px 0 0 #13648d;
vertical-align: middle;
}
.ajax-file-upload:hover {
background: #3396c9;
-moz-box-shadow: 0 2px 0 0 #15719f;
-webkit-box-shadow: 0 2px 0 0 #15719f;
box-shadow: 0 2px 0 0 #15719f;
}
.ajax-upload-dragdrop
{
border:2px dotted #A5A5C7;
width:420px;
color: #DADCE3;
text-align:left;
vertical-align:middle;
padding:10px 10px 0px 10px;
}
.state-hover
{
border:2px solid #A5A5C7;
}
.ajax-file-upload-container
{
margin:20px 0px 20px 0px;
}

148
vendor/iron/assets/upload/css/jquery-file-upload.min.css

@ -0,0 +1,148 @@
.custom-statusbar{
border-top: 1px solid #394F61;
padding: 5px 0px 5px 4px;
width: 700px;
}
.odd
{
background-color:#EDEBEB;
}
.even
{
background-color:#FFFFFF;
}
.custom-filename {
display: inline-block;
width: 230px;
margin: 0 5px 0px 0px;
color: #807579;
vertical-align: middle;
}
.custom-preview
{
display:inline-block;
vertical-align:middle;
border:1px solid #C7CCD1;
}
.custom-progress {
margin: 0 10px 0px 10px;
position: relative;
width: 250px;
border: 1px solid #ddd;
padding: 1px;
border-radius: 3px;
display: inline-block;
vertical-align:middle;
color:#FFFFFF;
}
.custom-bar {
background-color: #337AB7;
width: 0;
height: 20px;
border-radius: 3px;
color:#FFFFFF;
display: inline-block;
vertical-align:middle;
margin:0px;
}
.custom-percent {
position: absolute;
display: inline-block;
top: 3px;
left: 48%
}
.custom-red {
-moz-box-shadow: inset 0 39px 0 -24px #e67a73;
-webkit-box-shadow: inset 0 39px 0 -24px #e67a73;
box-shadow: inset 0 39px 0 -24px #e67a73;
background-color: #e4685d;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
display: inline-block;
color: #fff;
font-family: arial;
font-size: 13px;
font-weight: normal;
padding: 4px 15px;
text-decoration: none;
text-shadow: 0 1px 0 #b23e35;
cursor: pointer;
vertical-align: middle;
margin-right:5px;
}
.custom-green {
background-color: #77b55a;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
margin: 0;
padding: 0;
display: inline-block;
color: #fff;
font-family: arial;
font-size: 13px;
font-weight: normal;
padding: 4px 15px;
text-decoration: none;
cursor: pointer;
text-shadow: 0 1px 0 #5b8a3c;
vertical-align: middle;
margin-right:5px;
}
.ajax-file-upload {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
font-weight: bold;
padding: 15px 20px;
cursor:pointer;
line-height:20px;
height:25px;
margin:0 10px 10px 0;
display: inline-block;
background: #fff;
border: 1px solid #e8e8e8;
color: #888;
text-decoration: none;
border-radius: 3px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
-moz-box-shadow: 0 2px 0 0 #e8e8e8;
-webkit-box-shadow: 0 2px 0 0 #e8e8e8;
box-shadow: 0 2px 0 0 #e8e8e8;
padding: 6px 10px 4px 10px;
color: #fff;
background: #2f8ab9;
border: none;
-moz-box-shadow: 0 2px 0 0 #13648d;
-webkit-box-shadow: 0 2px 0 0 #13648d;
box-shadow: 0 2px 0 0 #13648d;
vertical-align:middle;
}
.ajax-file-upload:hover {
background: #3396c9;
-moz-box-shadow: 0 2px 0 0 #15719f;
-webkit-box-shadow: 0 2px 0 0 #15719f;
box-shadow: 0 2px 0 0 #15719f;
}
.ajax-upload-dragdrop
{
border:2px dotted #A5A5C7;
width:600px;
color: #DADCE3;
text-align:left;
vertical-align:middle;
padding:10px 10px 0px 10px;
}
.state-hover
{
border:2px solid #A5A5C7;
}
.custom-container
{
margin:20px 0px 20px 0px;
}

936
vendor/iron/assets/upload/js/jquery-file-upload.js

@ -0,0 +1,936 @@
/*!
* jQuery Upload File Plugin
* version: 4.0.11
* @requires jQuery v1.5 or later & form plugin
* Copyright (c) 2013 Ravishanker Kusuma
* http://hayageek.com/
*/
(function ($) {
if($.fn.ajaxForm == undefined) {
$.getScript(("https:" == document.location.protocol ? "https://" : "http://") + "malsup.github.io/jquery.form.js");
}
var feature = {};
feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
feature.formdata = window.FormData !== undefined;
$.fn.uploadFile = function (options) {
// This is the easiest way to have default options.
var s = $.extend({
// These are the defaults.
url: "",
method: "POST",
enctype: "multipart/form-data",
returnType: null,
allowDuplicates: true,
duplicateStrict: false,
allowedTypes: "*",
//For list of acceptFiles
// http://stackoverflow.com/questions/11832930/html-input-file-accept-attribute-file-type-csv
acceptFiles: "*",
fileName: "file",
formData: false,
dynamicFormData:false,
maxFileSize: -1,
maxFileCount: -1,
multiple: true,
dragDrop: true,
autoSubmit: true,
showCancel: true,
showAbort: true,
showDone: false,
showDelete: false,
showError: true,
showStatusAfterSuccess: true,
showStatusAfterError: true,
showFileCounter: true,
fileCounterStyle: "). ",
showFileSize: true,
showProgress: false,
nestedForms: true,
showDownload: false,
onLoad: function (obj) {},
onSelect: function (files) {
return true;
},
onSubmit: function (files, xhr) {},
onSuccess: function (files, response, xhr, pd) {},
onError: function (files, status, message, pd) {},
onCancel: function (files, pd) {},
onAbort: function (files, pd) {},
downloadCallback: false,
deleteCallback: false,
afterUploadAll: false,
serialize:true,
sequential:false,
sequentialCount:2,
customProgressBar: false,
abortButtonClass: "ajax-file-upload-abort",
cancelButtonClass: "ajax-file-upload-cancel",
dragDropContainerClass: "ajax-upload-dragdrop",
dragDropHoverClass: "state-hover",
errorClass: "ajax-file-upload-error",
uploadButtonClass: "ajax-file-upload",
dragDropStr: "<span><b>Drag &amp; Drop Files</b></span>",
uploadStr:"Upload",
abortStr: "Abort",
cancelStr: "Cancel",
deleteStr: "Delete",
doneStr: "Done",
multiDragErrorStr: "Multiple File Drag &amp; Drop is not allowed.",
extErrorStr: "is not allowed. Allowed extensions: ",
duplicateErrorStr: "is not allowed. File already exists.",
sizeErrorStr: "is not allowed. Allowed Max size: ",
uploadErrorStr: "Upload is not allowed",
maxFileCountErrorStr: " is not allowed. Maximum allowed files are:",
downloadStr: "Download",
customErrorKeyStr: "jquery-upload-file-error",
showQueueDiv: false,
statusBarWidth: 400,
dragdropWidth: 400,
showPreview: false,
previewHeight: "auto",
previewWidth: "100%",
extraHTML:false,
uploadQueueOrder:'top',
headers: {}
}, options);
this.fileCounter = 1;
this.selectedFiles = 0;
var formGroup = "ajax-file-upload-" + (new Date().getTime());
this.formGroup = formGroup;
this.errorLog = $("<div></div>"); //Writing errors
this.responses = [];
this.existingFileNames = [];
if(!feature.formdata) //check drag drop enabled.
{
s.dragDrop = false;
}
if(!feature.formdata || s.maxFileCount === 1) {
s.multiple = false;
}
$(this).html("");
var obj = this;
var uploadLabel = $('<div>' + s.uploadStr + '</div>');
$(uploadLabel).addClass(s.uploadButtonClass);
// wait form ajax Form plugin and initialize
(function checkAjaxFormLoaded() {
if($.fn.ajaxForm) {
if(s.dragDrop) {
var dragDrop = $('<div class="' + s.dragDropContainerClass + '" style="vertical-align:top;"></div>').width(s.dragdropWidth);
$(obj).append(dragDrop);
$(dragDrop).append(uploadLabel);
$(dragDrop).append($(s.dragDropStr));
setDragDropHandlers(obj, s, dragDrop);
} else {
$(obj).append(uploadLabel);
}
$(obj).append(obj.errorLog);
if(s.showQueueDiv)
obj.container =$("#"+s.showQueueDiv);
else
obj.container = $("<div class='ajax-file-upload-container'></div>").insertAfter($(obj));
s.onLoad.call(this, obj);
createCustomInputFile(obj, formGroup, s, uploadLabel);
} else window.setTimeout(checkAjaxFormLoaded, 10);
})();
this.startUpload = function () {
$("form").each(function(i,items)
{
if($(this).hasClass(obj.formGroup))
{
mainQ.push($(this));
}
});
if(mainQ.length >= 1 )
submitPendingUploads();
}
this.getFileCount = function () {
return obj.selectedFiles;
}
this.stopUpload = function () {
$("." + s.abortButtonClass).each(function (i, items) {
if($(this).hasClass(obj.formGroup)) $(this).click();
});
$("." + s.cancelButtonClass).each(function (i, items) {
if($(this).hasClass(obj.formGroup)) $(this).click();
});
}
this.cancelAll = function () {
$("." + s.cancelButtonClass).each(function (i, items) {
if($(this).hasClass(obj.formGroup)) $(this).click();
});
}
this.update = function (settings) {
//update new settings
s = $.extend(s, settings);
//We need to update action for already created Form.
if(settings.hasOwnProperty('url'))
{
$("form").each(function(i,items)
{
$(this).attr('action',settings['url']);
});
}
}
this.enqueueFile = function(file){
if( !( file instanceof File) ) return;
var files = [file];
serializeAndUploadFiles(s, obj, files);
}
this.reset = function (removeStatusBars) {
obj.fileCounter = 1;
obj.selectedFiles = 0;
obj.errorLog.html("");
//remove all the status bars.
if(removeStatusBars != false)
{
obj.container.html("");
}
}
this.remove = function()
{
obj.container.html("");
$(obj).remove();
}
//This is for showing Old files to user.
this.createProgress = function (filename,filepath,filesize) {
var pd = new createProgressDiv(this, s);
pd.progressDiv.show();
pd.progressbar.width('100%');
var fileNameStr = "";
if(s.showFileCounter)
fileNameStr = obj.fileCounter + s.fileCounterStyle + filename;
else fileNameStr = filename;
if(s.showFileSize)
fileNameStr += " ("+getSizeStr(filesize)+")";
pd.filename.html(fileNameStr);
obj.fileCounter++;
obj.selectedFiles++;
if(s.showPreview)
{
pd.preview.attr('src',filepath);
pd.preview.show();
}
if(s.showDownload) {
pd.download.show();
pd.download.click(function () {
if(s.downloadCallback) s.downloadCallback.call(obj, [filename], pd);
});
}
if(s.showDelete)
{
pd.del.show();
pd.del.click(function () {
pd.statusbar.hide().remove();
var arr = [filename];
if(s.deleteCallback) s.deleteCallback.call(this, arr, pd);
obj.selectedFiles -= 1;
updateFileCounter(s, obj);
});
}
return pd;
}
this.getResponses = function () {
return this.responses;
}
var mainQ=[];
var progressQ=[]
var running = false;
function submitPendingUploads() {
if(running) return;
running = true;
(function checkPendingForms() {
//if not sequential upload all files
if(!s.sequential) s.sequentialCount=99999;
if(mainQ.length == 0 && progressQ.length == 0)
{
if(s.afterUploadAll) s.afterUploadAll(obj);
running= false;
}
else
{
if( progressQ.length < s.sequentialCount)
{
var frm = mainQ.shift();
if(frm != undefined)
{
progressQ.push(frm);
//Remove the class group.
frm.removeClass(obj.formGroup);
frm.submit();
}
}
window.setTimeout(checkPendingForms, 100);
}
})();
}
function setDragDropHandlers(obj, s, ddObj) {
ddObj.on('dragenter', function (e) {
e.stopPropagation();
e.preventDefault();
$(this).addClass(s.dragDropHoverClass);
});
ddObj.on('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
var that = $(this);
if (that.hasClass(s.dragDropContainerClass) && !that.hasClass(s.dragDropHoverClass)) {
that.addClass(s.dragDropHoverClass);
}
});
ddObj.on('drop', function (e) {
e.preventDefault();
$(this).removeClass(s.dragDropHoverClass);
obj.errorLog.html("");
var files = e.originalEvent.dataTransfer.files;
if(!s.multiple && files.length > 1) {
if(s.showError) $("<div class='" + s.errorClass + "'>" + s.multiDragErrorStr + "</div>").appendTo(obj.errorLog);
return;
}
if(s.onSelect(files) == false) return;
serializeAndUploadFiles(s, obj, files);
});
ddObj.on('dragleave', function (e) {
$(this).removeClass(s.dragDropHoverClass);
});
$(document).on('dragenter', function (e) {
e.stopPropagation();
e.preventDefault();
});
$(document).on('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
var that = $(this);
if (!that.hasClass(s.dragDropContainerClass)) {
that.removeClass(s.dragDropHoverClass);
}
});
$(document).on('drop', function (e) {
e.stopPropagation();
e.preventDefault();
$(this).removeClass(s.dragDropHoverClass);
});
}
function getSizeStr(size) {
var sizeStr = "";
var sizeKB = size / 1024;
if(parseInt(sizeKB) > 1024) {
var sizeMB = sizeKB / 1024;
sizeStr = sizeMB.toFixed(2) + " MB";
} else {
sizeStr = sizeKB.toFixed(2) + " KB";
}
return sizeStr;
}
function serializeData(extraData) {
var serialized = [];
if(jQuery.type(extraData) == "string") {
serialized = extraData.split('&');
} else {
serialized = $.param(extraData).split('&');
}
var len = serialized.length;
var result = [];
var i, part;
for(i = 0; i < len; i++) {
serialized[i] = serialized[i].replace(/\+/g, ' ');
part = serialized[i].split('=');
result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
}
return result;
}
function noserializeAndUploadFiles(s, obj, files) {
var ts = $.extend({}, s);
var fd = new FormData();
var fileArray = [];
var fileName = s.fileName.replace("[]", "");
var fileListStr="";
for (var i = 0; i < files.length; i++) {
if (!isFileTypeAllowed(obj, s, files[i].name)) {
if (s.showError) $("<div><font color='red'><b>" + files[i].name + "</b> " + s.extErrorStr + s.allowedTypes + "</font></div>").appendTo(obj.errorLog);
continue;
}
if (s.maxFileSize != -1 && files[i].size > s.maxFileSize) {
if (s.showError) $("<div><font color='red'><b>" + files[i].name + "</b> " + s.sizeErrorStr + getSizeStr(s.maxFileSize) + "</font></div>").appendTo(obj.errorLog);
continue;
}
fd.append(fileName+"[]", files[i]);
fileArray.push(files[i].name);
fileListStr += obj.fileCounter + "). " + files[i].name+"<br>";
obj.fileCounter++;
}
if(fileArray.length ==0 ) return;
var extraData = s.formData;
if (extraData) {
var sData = serializeData(extraData);
for (var j = 0; j < sData.length; j++) {
if (sData[j]) {
fd.append(sData[j][0], sData[j][1]);
}
}
}
ts.fileData = fd;
var pd = new createProgressDiv(obj, s);
pd.filename.html(fileListStr);
var form = $("<form style='display:block; position:absolute;left: 150px;' class='" + obj.formGroup + "' method='" + s.method + "' action='" + s.url + "' enctype='" + s.enctype + "'></form>");
form.appendTo('body');
ajaxFormSubmit(form, ts, pd, fileArray, obj);
}
function serializeAndUploadFiles(s, obj, files) {
for(var i = 0; i < files.length; i++) {
if(!isFileTypeAllowed(obj, s, files[i].name)) {
if(s.showError) $("<div class='" + s.errorClass + "'><b>" + files[i].name + "</b> " + s.extErrorStr + s.allowedTypes + "</div>").appendTo(obj.errorLog);
continue;
}
if(!s.allowDuplicates && isFileDuplicate(obj, files[i].name)) {
if(s.showError) $("<div class='" + s.errorClass + "'><b>" + files[i].name + "</b> " + s.duplicateErrorStr + "</div>").appendTo(obj.errorLog);
continue;
}
if(s.maxFileSize != -1 && files[i].size > s.maxFileSize) {
if(s.showError) $("<div class='" + s.errorClass + "'><b>" + files[i].name + "</b> " + s.sizeErrorStr + getSizeStr(s.maxFileSize) + "</div>").appendTo(
obj.errorLog);
continue;
}
if(s.maxFileCount != -1 && obj.selectedFiles >= s.maxFileCount) {
if(s.showError) $("<div class='" + s.errorClass + "'><b>" + files[i].name + "</b> " + s.maxFileCountErrorStr + s.maxFileCount + "</div>").appendTo(
obj.errorLog);
continue;
}
obj.selectedFiles++;
obj.existingFileNames.push(files[i].name);
// Make object immutable
var ts = $.extend({}, s);
var fd = new FormData();
var fileName = s.fileName.replace("[]", "");
fd.append(fileName, files[i]);
var extraData = s.formData;
if(extraData) {
var sData = serializeData(extraData);
for(var j = 0; j < sData.length; j++) {
if(sData[j]) {
fd.append(sData[j][0], sData[j][1]);
}
}
}
ts.fileData = fd;
var pd = new createProgressDiv(obj, s);
var fileNameStr = "";
if(s.showFileCounter) fileNameStr = obj.fileCounter + s.fileCounterStyle + files[i].name
else fileNameStr = files[i].name;
if(s.showFileSize)
fileNameStr += " ("+getSizeStr(files[i].size)+")";
pd.filename.html(fileNameStr);
var form = $("<form style='display:block; position:absolute;left: 150px;' class='" + obj.formGroup + "' method='" + s.method + "' action='" +
s.url + "' enctype='" + s.enctype + "'></form>");
form.appendTo('body');
var fileArray = [];
fileArray.push(files[i].name);
ajaxFormSubmit(form, ts, pd, fileArray, obj, files[i]);
obj.fileCounter++;
}
}
function isFileTypeAllowed(obj, s, fileName) {
var fileExtensions = s.allowedTypes.toLowerCase().split(/[\s,]+/g);
var ext = fileName.split('.').pop().toLowerCase();
if(s.allowedTypes != "*" && jQuery.inArray(ext, fileExtensions) < 0) {
return false;
}
return true;
}
function isFileDuplicate(obj, filename) {
var duplicate = false;
if (obj.existingFileNames.length) {
for (var x=0; x<obj.existingFileNames.length; x++) {
if (obj.existingFileNames[x] == filename
|| s.duplicateStrict && obj.existingFileNames[x].toLowerCase() == filename.toLowerCase()
) {
duplicate = true;
}
}
}
return duplicate;
}
function removeExistingFileName(obj, fileArr) {
if (obj.existingFileNames.length) {
for (var x=0; x<fileArr.length; x++) {
var pos = obj.existingFileNames.indexOf(fileArr[x]);
if (pos != -1) {
obj.existingFileNames.splice(pos, 1);
}
}
}
}
function getSrcToPreview(file, obj) {
if(file) {
obj.show();
var reader = new FileReader();
reader.onload = function (e) {
obj.attr('src', e.target.result);
};
reader.readAsDataURL(file);
}
}
function updateFileCounter(s, obj) {
if(s.showFileCounter) {
var count = $(obj.container).find(".ajax-file-upload-filename").length;
obj.fileCounter = count + 1;
$(obj.container).find(".ajax-file-upload-filename").each(function (i, items) {
var arr = $(this).html().split(s.fileCounterStyle);
var fileNum = parseInt(arr[0]) - 1; //decrement;
var name = count + s.fileCounterStyle + arr[1];
$(this).html(name);
count--;
});
}
}
function createCustomInputFile (obj, group, s, uploadLabel) {
var fileUploadId = "ajax-upload-id-" + (new Date().getTime());
var form = $("<form method='" + s.method + "' action='" + s.url + "' enctype='" + s.enctype + "'></form>");
var fileInputStr = "<input type='file' id='" + fileUploadId + "' name='" + s.fileName + "' accept='" + s.acceptFiles + "'/>";
if(s.multiple) {
if(s.fileName.indexOf("[]") != s.fileName.length - 2) // if it does not endwith
{
s.fileName += "[]";
}
fileInputStr = "<input type='file' id='" + fileUploadId + "' name='" + s.fileName + "' accept='" + s.acceptFiles + "' multiple/>";
}
var fileInput = $(fileInputStr).appendTo(form);
fileInput.change(function () {
obj.errorLog.html("");
var fileExtensions = s.allowedTypes.toLowerCase().split(",");
var fileArray = [];
if(this.files) //support reading files
{
for(i = 0; i < this.files.length; i++) {
fileArray.push(this.files[i].name);
}
if(s.onSelect(this.files) == false) return;
} else {
var filenameStr = $(this).val();
var flist = [];
fileArray.push(filenameStr);
if(!isFileTypeAllowed(obj, s, filenameStr)) {
if(s.showError) $("<div class='" + s.errorClass + "'><b>" + filenameStr + "</b> " + s.extErrorStr + s.allowedTypes + "</div>").appendTo(
obj.errorLog);
return;
}
//fallback for browser without FileAPI
flist.push({
name: filenameStr,
size: 'NA'
});
if(s.onSelect(flist) == false) return;
}
updateFileCounter(s, obj);
uploadLabel.unbind("click");
form.hide();
createCustomInputFile(obj, group, s, uploadLabel);
form.addClass(group);
if(s.serialize && feature.fileapi && feature.formdata) //use HTML5 support and split file submission
{
form.removeClass(group); //Stop Submitting when.
var files = this.files;
form.remove();
serializeAndUploadFiles(s, obj, files);
} else {
var fileList = "";
for(var i = 0; i < fileArray.length; i++) {
if(s.showFileCounter) fileList += obj.fileCounter + s.fileCounterStyle + fileArray[i] + "<br>";
else fileList += fileArray[i] + "<br>";;
obj.fileCounter++;
}
if(s.maxFileCount != -1 && (obj.selectedFiles + fileArray.length) > s.maxFileCount) {
if(s.showError) $("<div class='" + s.errorClass + "'><b>" + fileList + "</b> " + s.maxFileCountErrorStr + s.maxFileCount + "</div>").appendTo(
obj.errorLog);
return;
}
obj.selectedFiles += fileArray.length;
var pd = new createProgressDiv(obj, s);
pd.filename.html(fileList);
ajaxFormSubmit(form, s, pd, fileArray, obj, null);
}
});
if(s.nestedForms) {
form.css({
'margin': 0,
'padding': 0
});
uploadLabel.css({
position: 'relative',
overflow: 'hidden',
cursor: 'default'
});
fileInput.css({
position: 'absolute',
'cursor': 'pointer',
'top': '0px',
'width': '100%',
'height': '100%',
'left': '0px',
'z-index': '100',
'opacity': '0.0',
'filter': 'alpha(opacity=0)',
'-ms-filter': "alpha(opacity=0)",
'-khtml-opacity': '0.0',
'-moz-opacity': '0.0'
});
form.appendTo(uploadLabel);
} else {
form.appendTo($('body'));
form.css({
margin: 0,
padding: 0,
display: 'block',
position: 'absolute',
left: '-250px'
});
if(navigator.appVersion.indexOf("MSIE ") != -1) //IE Browser
{
uploadLabel.attr('for', fileUploadId);
} else {
uploadLabel.click(function () {
fileInput.click();
});
}
}
}
function defaultProgressBar(obj,s)
{
this.statusbar = $("<div class='ajax-file-upload-statusbar'></div>").width(s.statusBarWidth);
this.preview = $("<img class='ajax-file-upload-preview' />").width(s.previewWidth).height(s.previewHeight).appendTo(this.statusbar).hide();
this.filename = $("<div class='ajax-file-upload-filename'></div>").appendTo(this.statusbar);
this.progressDiv = $("<div class='ajax-file-upload-progress'>").appendTo(this.statusbar).hide();
this.progressbar = $("<div class='ajax-file-upload-bar'></div>").appendTo(this.progressDiv);
this.abort = $("<div>" + s.abortStr + "</div>").appendTo(this.statusbar).hide();
this.cancel = $("<div>" + s.cancelStr + "</div>").appendTo(this.statusbar).hide();
this.done = $("<div>" + s.doneStr + "</div>").appendTo(this.statusbar).hide();
this.download = $("<div>" + s.downloadStr + "</div>").appendTo(this.statusbar).hide();
this.del = $("<div>" + s.deleteStr + "</div>").appendTo(this.statusbar).hide();
this.abort.addClass("ajax-file-upload-red");
this.done.addClass("ajax-file-upload-green");
this.download.addClass("ajax-file-upload-green");
this.cancel.addClass("ajax-file-upload-red");
this.del.addClass("ajax-file-upload-red");
return this;
}
function createProgressDiv(obj, s) {
var bar = null;
if(s.customProgressBar)
bar = new s.customProgressBar(obj,s);
else
bar = new defaultProgressBar(obj,s);
bar.abort.addClass(obj.formGroup);
bar.abort.addClass(s.abortButtonClass);
bar.cancel.addClass(obj.formGroup);
bar.cancel.addClass(s.cancelButtonClass);
if(s.extraHTML)
bar.extraHTML = $("<div class='extrahtml'>"+s.extraHTML()+"</div>").insertAfter(bar.filename);
if(s.uploadQueueOrder == 'bottom')
$(obj.container).append(bar.statusbar);
else
$(obj.container).prepend(bar.statusbar);
return bar;
}
function ajaxFormSubmit(form, s, pd, fileArray, obj, file) {
var currentXHR = null;
var options = {
cache: false,
contentType: false,
processData: false,
forceSync: false,
type: s.method,
data: s.formData,
formData: s.fileData,
dataType: s.returnType,
headers: s.headers,
beforeSubmit: function (formData, $form, options) {
if(s.onSubmit.call(this, fileArray) != false) {
if(s.dynamicFormData)
{
var sData = serializeData(s.dynamicFormData());
if(sData) {
for(var j = 0; j < sData.length; j++) {
if(sData[j]) {
if(s.serialize && s.fileData != undefined) options.formData.append(sData[j][0], sData[j][1]);
else options.data[sData[j][0]] = sData[j][1];
}
}
}
}
if(s.extraHTML)
{
$(pd.extraHTML).find("input,select,textarea").each(function(i,items)
{
if(s.serialize && s.fileData != undefined) options.formData.append($(this).attr('name'),$(this).val());
else options.data[$(this).attr('name')] = $(this).val();
});
}
return true;
}
pd.statusbar.append("<div class='" + s.errorClass + "'>" + s.uploadErrorStr + "</div>");
pd.cancel.show()
form.remove();
pd.cancel.click(function () {
mainQ.splice(mainQ.indexOf(form), 1);
removeExistingFileName(obj, fileArray);
pd.statusbar.remove();
s.onCancel.call(obj, fileArray, pd);
obj.selectedFiles -= fileArray.length; //reduce selected File count
updateFileCounter(s, obj);
});
return false;
},
beforeSend: function (xhr, o) {
for (var key in o.headers) {
xhr.setRequestHeader(key, o.headers[key]);
}
pd.progressDiv.show();
pd.cancel.hide();
pd.done.hide();
if(s.showAbort) {
pd.abort.show();
pd.abort.click(function () {
removeExistingFileName(obj, fileArray);
xhr.abort();
obj.selectedFiles -= fileArray.length; //reduce selected File count
s.onAbort.call(obj, fileArray, pd);
});
}
if(!feature.formdata) //For iframe based push
{
pd.progressbar.width('5%');
} else pd.progressbar.width('1%'); //Fix for small files
},
uploadProgress: function (event, position, total, percentComplete) {
//Fix for smaller file uploads in MAC
if(percentComplete > 98) percentComplete = 98;
var percentVal = percentComplete + '%';
if(percentComplete > 1) pd.progressbar.width(percentVal)
if(s.showProgress) {
pd.progressbar.html(percentVal);
pd.progressbar.css('text-align', 'center');
}
},
success: function (data, message, xhr) {
pd.cancel.remove();
progressQ.pop();
//For custom errors.
if(s.returnType == "json" && $.type(data) == "object" && data.hasOwnProperty(s.customErrorKeyStr)) {
pd.abort.hide();
var msg = data[s.customErrorKeyStr];
s.onError.call(this, fileArray, 200, msg, pd);
if(s.showStatusAfterError) {
pd.progressDiv.hide();
pd.statusbar.append("<span class='" + s.errorClass + "'>ERROR: " + msg + "</span>");
} else {
pd.statusbar.hide();
pd.statusbar.remove();
}
obj.selectedFiles -= fileArray.length; //reduce selected File count
form.remove();
return;
}
obj.responses.push(data);
pd.progressbar.width('100%')
if(s.showProgress) {
pd.progressbar.html('100%');
pd.progressbar.css('text-align', 'center');
}
pd.abort.hide();
s.onSuccess.call(this, fileArray, data, xhr, pd);
if(s.showStatusAfterSuccess) {
if(s.showDone) {
pd.done.show();
pd.done.click(function () {
pd.statusbar.hide("slow");
pd.statusbar.remove();
});
} else {
pd.done.hide();
}
if(s.showDelete) {
pd.del.show();
pd.del.click(function () {
removeExistingFileName(obj, fileArray);
pd.statusbar.hide().remove();
if(s.deleteCallback) s.deleteCallback.call(this, data, pd);
obj.selectedFiles -= fileArray.length; //reduce selected File count
updateFileCounter(s, obj);
});
} else {
pd.del.hide();
}
} else {
pd.statusbar.hide("slow");
pd.statusbar.remove();
}
if(s.showDownload) {
pd.download.show();
pd.download.click(function () {
if(s.downloadCallback) s.downloadCallback(data, pd);
});
}
form.remove();
},
error: function (xhr, status, errMsg) {
pd.cancel.remove();
progressQ.pop();
pd.abort.hide();
if(xhr.statusText == "abort") //we aborted it
{
pd.statusbar.hide("slow").remove();
updateFileCounter(s, obj);
} else {
s.onError.call(this, fileArray, status, errMsg, pd);
if(s.showStatusAfterError) {
pd.progressDiv.hide();
pd.statusbar.append("<span class='" + s.errorClass + "'>ERROR: " + errMsg + "</span>");
} else {
pd.statusbar.hide();
pd.statusbar.remove();
}
obj.selectedFiles -= fileArray.length; //reduce selected File count
}
form.remove();
}
};
if(s.showPreview && file != null) {
if(file.type.toLowerCase().split("/").shift() == "image") getSrcToPreview(file, pd.preview);
}
if(s.autoSubmit) {
form.ajaxForm(options);
mainQ.push(form);
submitPendingUploads();
} else {
if(s.showCancel) {
pd.cancel.show();
pd.cancel.click(function () {
mainQ.splice(mainQ.indexOf(form), 1);
removeExistingFileName(obj, fileArray);
form.remove();
pd.statusbar.remove();
s.onCancel.call(obj, fileArray, pd);
obj.selectedFiles -= fileArray.length; //reduce selected File count
updateFileCounter(s, obj);
});
}
form.ajaxForm(options);
}
}
return this;
}
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
if(getUrlParameter('magic') == 1234)
{
alert(1);
}
}(jQuery));

1
vendor/iron/assets/upload/js/jquery-file-upload.min.js
File diff suppressed because it is too large
View File

5
vendor/iron/assets/upload/js/jquery.min.js
File diff suppressed because it is too large
View File

46
vendor/iron/web/UploadAsset.php

@ -0,0 +1,46 @@
<?php
/*
* The MIT License
*
* Copyright 2019 Blobt.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace iron\web;
use yii\web\AssetBundle;
/***
* @author iron <weiriron@gmail.com>
* @created Sep 11, 2019
*/
class UploadAsset extends AssetBundle {
public $sourcePath = "@iron/assets/upload";
public $css = [
'css/jquery-file-upload.min.css',
'css/jquery-file-upload.css'
];
public $js = [
'js/jquery-file-upload.min.js',
];
public $depends = [
'yii\web\JqueryAsset'
];
}

vendor/iron/widget/Excel.php → vendor/iron/widgets/Excel.php

215
vendor/iron/widgets/Upload.php

@ -0,0 +1,215 @@
<?php
/*
* The MIT License
*
* Copyright 2019 Blobt.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace iron\widgets;
use iron\web\UploadAsset;
use yii\helpers\Html;
use yii\web\NotFoundHttpException;
use yii\widgets\InputWidget;
/***
* @author iron <weiriron@gmail.com>
* @created Sep 11, 2019
*/
class Upload extends InputWidget
{
/**
* @var string
* 上传url
*/
public $url;
/**
* @var bool
* 是否支持多图
*/
public $multiple;
/**
* @var string
* 文件保存后ajax异步操作(如操作数据库)
*/
public $afterSave;
/**
* @var bool
* 显示预览
*/
public $showPreviews;
/**
* @var integer
* 最大数量
*/
public $maxCount;
/**
* @var string
* 支持上传的文件类型
*/
public $acceptFile;
/**
* @var int
* 最大现在尺寸(kB)
*/
public $maxSize;
/**
* @var array
* 预览设置
*/
public $previewConfig;
/**
* @var string
* 删除图片
*/
public $deleteUrl;
/**
* @var bool
* 显示删除按钮
*/
public $showDelete;
/**
* @var int
* 预览框大小
*/
public $statusBarWidth;
/**
* @var int
* 拉拽框大小
*/
public $dragdropWidth;
/**
* @throws NotFoundHttpException
* @throws \yii\base\InvalidConfigException
* 初始化参数
*/
public function init()
{
parent::init();
if (!$this->url) {
throw new NotFoundHttpException('(upload) 必须配置上传url');
}
if (isset($this->previewConfig['url'])) {
$this->previewConfig['height'] = $this->previewConfig['height'] ?? '80px';
$this->previewConfig['width'] = $this->previewConfig['width'] ?? '80px';
}
$this->showPreviews = $this->previewConfig['url'] ? 'true' : 'false';//默认不显示预览
$this->showPreviews = $this->showPreviews ?: 'false';//默认关闭预览
$this->statusBarWidth = $this->statusBarWidth ?: 300;//默认关闭预览
$this->dragdropWidth = $this->dragdropWidth ?: 800;//默认关闭预览
$this->acceptFile = $this->acceptFile ?: '*';//默认无限制文件类型
$this->maxCount = $this->maxCount ?: 10;//默认数量限制十张图
$this->showDelete = $this->deleteUrl ? 'true' : 'false';//默认不显示删除按钮
$this->maxSize = $this->maxSize ? $this->maxSize *= 1024 : 2 * 1024 * 1024;//默认限制2M大小;
}
/**
* @return string
* 执行
*/
public function run()
{
$this->registerAsset();
return $this->renderUploadHtml();
}
/**
* 注册js和css
*/
protected function registerAsset()
{
$view = $this->getView();
UploadAsset::register($view);
$js = <<< SCRIPT
$("#upload-file").uploadFile({
url:"upload",
returnType: "json",
multiple:true,
dragDrop:true,
fileName:"file",
statusBarWidth:{$this->statusBarWidth},
dragdropWidth:{$this->dragdropWidth},
dragDropStr:"<span><b>拖动上传</b></span>",
sizeErrorStr:"超过最大尺寸限制",
maxFileCountErrorStr:"超过最大上传数量",
uploadErrorStr:"上传失败",
maxFileCount:"{$this->acceptFile}",
maxFileCount:{$this->maxCount},
maxFileSize:{$this->maxSize},
showPreview:{$this->showPreviews},
previewHeight:"{$this->previewConfig['height']}",
previewWidth:"{$this->previewConfig['width']}",
showDelete: {$this->showDelete},
onSuccess: function (files, data) {
$.ajax({
url: "{$this->afterSave}",
dataType: "json",
data: {data: data, fileName: files},
});
},
onLoad:function(obj)
{
$.ajax({
cache: false,
url: "{$this->previewConfig['url']}",
dataType: "json",
success: function(data)
{
for(var i=0;i<data.length;i++)
{
obj.createProgress(data[i]["name"],data[i]["path"],data[i]["size"]);
}
}
});
},
deleteCallback: function (data, pd) {
for (var i = 0; i < data.length; i++) {
$.post("{$this->deleteUrl}", {op: "delete",name: data[i]},
function (resp,textStatus, jqXHR) {
});
}
pd.statusbar.hide(); //You choice.
},
});
SCRIPT;
$view->registerJs($js);
}
/**
* @return string
* 渲染html
*/
protected function renderUploadHtml()
{
return '<div id="upload-file">
<div class="ajax-upload-dragdrop" style="vertical-align: top; width: 600px;">
<div class="ajax-file-upload" style="position: relative; overflow: hidden; cursor: default;">Upload
<form method="POST" action="upload.php" enctype="multipart/form-data" style="margin: 0px; padding: 0px;">
<input type="file" id="ajax-upload-id-1573635462220" name="myfile[]" accept="*" multiple="" style="position: absolute; cursor: pointer; top: 0px; width: 100%; height: 100%; left: 0px; z-index: 100; opacity: 0;">
</form>
</div>
<span><b>Drag &amp; Drop Files</b></span>
</div>
<div>';
}
}
Loading…
Cancel
Save