作者 Karson

新增会员首字母头像功能

新增文本框挺拽上传和粘贴上传
优化注册和登录的跳转
修复后台默认皮肤保存失效的BUG
... ... @@ -7,14 +7,15 @@ if (!function_exists('__')) {
/**
* 获取语言变量值
* @param string $name 语言变量名
* @param array $vars 动态变量值
* @param array $vars 动态变量值
* @param string $lang 语言
* @return mixed
*/
function __($name, $vars = [], $lang = '')
{
if (is_numeric($name) || !$name)
if (is_numeric($name) || !$name) {
return $name;
}
if (!is_array($vars)) {
$vars = func_get_args();
array_shift($vars);
... ... @@ -22,32 +23,31 @@ if (!function_exists('__')) {
}
return \think\Lang::get($name, $vars, $lang);
}
}
if (!function_exists('format_bytes')) {
/**
* 将字节转换为可读文本
* @param int $size 大小
* @param int $size 大小
* @param string $delimiter 分隔符
* @return string
*/
function format_bytes($size, $delimiter = '')
{
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
for ($i = 0; $size >= 1024 && $i < 6; $i++)
for ($i = 0; $size >= 1024 && $i < 6; $i++) {
$size /= 1024;
}
return round($size, 2) . $delimiter . $units[$i];
}
}
if (!function_exists('datetime')) {
/**
* 将时间戳转换为日期时间
* @param int $time 时间戳
* @param int $time 时间戳
* @param string $format 日期时间格式
* @return string
*/
... ... @@ -56,14 +56,13 @@ if (!function_exists('datetime')) {
$time = is_numeric($time) ? $time : strtotime($time);
return date($format, $time);
}
}
if (!function_exists('human_date')) {
/**
* 获取语义化时间
* @param int $time 时间
* @param int $time 时间
* @param int $local 本地时间
* @return string
*/
... ... @@ -71,27 +70,26 @@ if (!function_exists('human_date')) {
{
return \fast\Date::human($time, $local);
}
}
if (!function_exists('cdnurl')) {
/**
* 获取上传资源的CDN的地址
* @param string $url 资源相对地址
* @param string $url 资源相对地址
* @param boolean $domain 是否显示域名 或者直接传入域名
* @return string
*/
function cdnurl($url, $domain = false)
{
$url = preg_match("/^https?:\/\/(.*)/i", $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
if ($domain && !preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
$regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
$url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
if ($domain && !preg_match($regex, $url)) {
$domain = is_bool($domain) ? request()->domain() : $domain;
$url = $domain . $url;
}
return $url;
}
}
... ... @@ -109,36 +107,37 @@ if (!function_exists('is_really_writable')) {
}
if (is_dir($file)) {
$file = rtrim($file, '/') . '/' . md5(mt_rand());
if (($fp = @fopen($file, 'ab')) === FALSE) {
return FALSE;
if (($fp = @fopen($file, 'ab')) === false) {
return false;
}
fclose($fp);
@chmod($file, 0777);
@unlink($file);
return TRUE;
} elseif (!is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE) {
return FALSE;
return true;
} elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
return false;
}
fclose($fp);
return TRUE;
return true;
}
}
if (!function_exists('rmdirs')) {
/**
* 删除文件夹
* @param string $dirname 目录
* @param bool $withself 是否删除自身
* @param string $dirname 目录
* @param bool $withself 是否删除自身
* @return boolean
*/
function rmdirs($dirname, $withself = true)
{
if (!is_dir($dirname))
if (!is_dir($dirname)) {
return false;
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $fileinfo) {
... ... @@ -150,7 +149,6 @@ if (!function_exists('rmdirs')) {
}
return true;
}
}
if (!function_exists('copydirs')) {
... ... @@ -158,7 +156,7 @@ if (!function_exists('copydirs')) {
/**
* 复制文件夹
* @param string $source 源文件夹
* @param string $dest 目标文件夹
* @param string $dest 目标文件夹
*/
function copydirs($source, $dest)
{
... ... @@ -167,7 +165,9 @@ if (!function_exists('copydirs')) {
}
foreach (
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
) as $item
) {
if ($item->isDir()) {
$sontDir = $dest . DS . $iterator->getSubPathName();
... ... @@ -179,30 +179,28 @@ if (!function_exists('copydirs')) {
}
}
}
}
if (!function_exists('mb_ucfirst')) {
function mb_ucfirst($string)
{
return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
}
}
if (!function_exists('addtion')) {
/**
* 附加关联字段数据
* @param array $items 数据列表
* @param array $items 数据列表
* @param mixed $fields 渲染的来源字段
* @return array
*/
function addtion($items, $fields)
{
if (!$items || !$fields)
if (!$items || !$fields) {
return $items;
}
$fieldsArr = [];
if (!is_array($fields)) {
$arr = explode(',', $fields);
... ... @@ -260,14 +258,13 @@ if (!function_exists('addtion')) {
}
return $items;
}
}
if (!function_exists('var_export_short')) {
/**
* 返回打印数组结构
* @param string $var 数组
* @param string $var 数组
* @param string $indent 缩进字符
* @return string
*/
... ... @@ -288,8 +285,80 @@ if (!function_exists('var_export_short')) {
case "boolean":
return $var ? "TRUE" : "FALSE";
default:
return var_export($var, TRUE);
return var_export($var, true);
}
}
}
}
\ No newline at end of file
if (!function_exists('letter_avatar')) {
/**
* 首字母头像
* @param $text
* @return string
*/
function letter_avatar($text)
{
$total = unpack('L', hash('adler32', $text, true))[1];
$hue = $total % 360;
list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
$bg = "rgb({$r},{$g},{$b})";
$color = "#ffffff";
$first = mb_strtoupper(mb_substr($text, 0, 1));
$src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" fill="' . $color . '" text-anchor="middle" alignment-baseline="central">' . $first . '</text></svg>');
$value = 'data:image/svg+xml;base64,' . $src;
return $value;
}
}
if (!function_exists('hsv2rgb')) {
function hsv2rgb($h, $s, $v)
{
$r = $g = $b = 0;
$i = floor($h * 6);
$f = $h * 6 - $i;
$p = $v * (1 - $s);
$q = $v * (1 - $f * $s);
$t = $v * (1 - (1 - $f) * $s);
switch ($i % 6) {
case 0:
$r = $v;
$g = $t;
$b = $p;
break;
case 1:
$r = $q;
$g = $v;
$b = $p;
break;
case 2:
$r = $p;
$g = $v;
$b = $t;
break;
case 3:
$r = $p;
$g = $q;
$b = $v;
break;
case 4:
$r = $t;
$g = $p;
$b = $v;
break;
case 5:
$r = $v;
$g = $p;
$b = $q;
break;
}
return [
floor($r * 255),
floor($g * 255),
floor($b * 255)
];
}
}
... ...
... ... @@ -39,7 +39,12 @@ class User extends Model
*/
public function getAvatarAttr($value, $data)
{
return $value ? $value : '/assets/img/avatar.png';
if (!$value) {
//如果不需要启用首字母头像,请使用
//$value = '/assets/img/avatar.png';
$value = letter_avatar($data['nickname']);
}
return $value;
}
/**
... ...
... ... @@ -27,11 +27,6 @@ class User extends Frontend
$this->error(__('User center already closed'));
}
$ucenter = get_addon_info('ucenter');
if ($ucenter && $ucenter['state']) {
include ADDON_PATH . 'ucenter' . DS . 'uc.php';
}
//监听注册登录注销的事件
Hook::add('user_login_successed', function ($user) use ($auth) {
$expire = input('post.keeplogin') ? 30 * 86400 : 0;
... ... @@ -82,7 +77,7 @@ class User extends Frontend
{
$url = $this->request->request('url');
if ($this->auth->id) {
$this->success(__('You\'ve logged in, do not login again'), $url);
$this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
}
if ($this->request->isPost()) {
$username = $this->request->post('username');
... ... @@ -124,13 +119,7 @@ class User extends Frontend
$this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
}
if ($this->auth->register($username, $password, $email, $mobile)) {
$synchtml = '';
////////////////同步到Ucenter////////////////
if (defined('UC_STATUS') && UC_STATUS) {
$uc = new \addons\ucenter\library\client\Client();
$synchtml = $uc->uc_user_synregister($this->auth->id, $password);
}
$this->success(__('Sign up successful') . $synchtml, $url ? $url : url('user/index'));
$this->success(__('Sign up successful'), $url ? $url : url('user/index'));
} else {
$this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
}
... ... @@ -153,7 +142,7 @@ class User extends Frontend
{
$url = $this->request->request('url');
if ($this->auth->id) {
$this->success(__('You\'ve logged in, do not login again'), $url);
$this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
}
if ($this->request->isPost()) {
$account = $this->request->post('account');
... ... @@ -184,13 +173,7 @@ class User extends Frontend
return false;
}
if ($this->auth->login($account, $password)) {
$synchtml = '';
////////////////同步到Ucenter////////////////
if (defined('UC_STATUS') && UC_STATUS) {
$uc = new \addons\ucenter\library\client\Client();
$synchtml = $uc->uc_user_synlogin($this->auth->id);
}
$this->success(__('Logged in successful') . $synchtml, $url ? $url : url('user/index'));
$this->success(__('Logged in successful'), $url ? $url : url('user/index'));
} else {
$this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
}
... ... @@ -213,13 +196,7 @@ class User extends Frontend
{
//注销本站
$this->auth->logout();
$synchtml = '';
////////////////同步到Ucenter////////////////
if (defined('UC_STATUS') && UC_STATUS) {
$uc = new \addons\ucenter\library\client\Client();
$synchtml = $uc->uc_user_synlogout();
}
$this->success(__('Logout successful') . $synchtml, url('user/index'));
$this->success(__('Logout successful'), url('user/index'));
}
/**
... ... @@ -270,13 +247,7 @@ class User extends Frontend
$ret = $this->auth->changepwd($newpassword, $oldpassword);
if ($ret) {
$synchtml = '';
////////////////同步到Ucenter////////////////
if (defined('UC_STATUS') && UC_STATUS) {
$uc = new \addons\ucenter\library\client\Client();
$synchtml = $uc->uc_user_synlogout();
}
$this->success(__('Reset password successful') . $synchtml, url('user/login'));
$this->success(__('Reset password successful'), url('user/login'));
} else {
$this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
}
... ...
... ... @@ -354,7 +354,7 @@ define(['jquery', 'bootstrap', 'backend', 'addtabs', 'adminlte', 'form'], functi
function setup() {
var tmp = localStorage.getItem('skin');
if (tmp && $.inArray(tmp, my_skins))
if (tmp && $.inArray(tmp, my_skins) != -1)
change_skin(tmp);
// 皮肤切换
... ...
... ... @@ -95,8 +95,14 @@ define(['jquery', 'bootstrap', 'toastr', 'layer', 'lang'], function ($, undefine
return url;
},
//获取修复后可访问的cdn链接
cdnurl: function (url) {
return /^(?:[a-z]+:)?\/\//i.test(url) ? url : Config.upload.cdnurl + url;
cdnurl: function (url, domain) {
var rule = new RegExp("^((?:[a-z]+:)?\\/\\/|data:image\\/)", "i");
var url = rule.test(url) ? url : Config.upload.cdnurl + url;
if (domain && !rule.test(url)) {
domain = typeof domain === 'string' ? domain : location.origin;
url = domain + url;
}
return url;
},
//查询Url参数
query: function (name, url) {
... ...
define(['jquery', 'bootstrap', 'plupload', 'template'], function ($, undefined, Plupload, Template) {
var Upload = {
list: {},
config: {
container: document.body,
classname: '.plupload:not([initialized])',
previewtpl: '<li class="col-xs-3"><a href="<%=fullurl%>" data-url="<%=url%>" target="_blank" class="thumbnail"><img src="<%=fullurl%>" onerror="this.src=\'https://tool.fastadmin.net/icon/\'+\'<%=fullurl%>\'.split(\'.\').pop()+\'.png\';this.onerror=null;" class="img-responsive"></a><a href="javascript:;" class="btn btn-danger btn-xs btn-trash"><i class="fa fa-trash"></i></a></li>',
},
events: {
onInit: function (up) {
//修复少数安卓浏览器无法上传图片的Bug
var input = $("input[type=file]", $(up.settings.button).next());
if (input && input.prop("accept").match(/image\/jpeg/)) {
input.prop("accept", "image/jpg," + input.prop("accept"));
}
},
//初始化完成
onPostInit: function (up) {
list: {},
config: {
container: document.body,
classname: '.plupload:not([initialized])',
previewtpl: '<li class="col-xs-3"><a href="<%=fullurl%>" data-url="<%=url%>" target="_blank" class="thumbnail"><img src="<%=fullurl%>" onerror="this.src=\'https://tool.fastadmin.net/icon/\'+\'<%=fullurl%>\'.split(\'.\').pop()+\'.png\';this.onerror=null;" class="img-responsive"></a><a href="javascript:;" class="btn btn-danger btn-xs btn-trash"><i class="fa fa-trash"></i></a></li>',
},
//文件添加成功后
onFileAdded: function (up, files) {
var button = up.settings.button;
$(button).data("bakup-html", $(button).html());
var maxcount = $(button).data("maxcount");
var input_id = $(button).data("input-id") ? $(button).data("input-id") : "";
maxcount = typeof maxcount !== "undefined" ? maxcount : 0;
if (maxcount > 0 && input_id) {
var inputObj = $("#" + input_id);
if (inputObj.size() > 0) {
var value = $.trim(inputObj.val());
var nums = value === '' ? 0 : value.split(/\,/).length;
var remains = maxcount - nums;
if (files.length > remains) {
for (var i = 0; i < files.length; i++) {
up.removeFile(files[i]);
}
Toastr.error(__('You can upload up to %d file%s', remains));
return false;
}
events: {
onInit: function (up) {
//修复少数安卓浏览器无法上传图片的Bug
var input = $("input[type=file]", $(up.settings.button).next());
if (input && input.prop("accept").match(/image\/jpeg/)) {
input.prop("accept", "image/jpg," + input.prop("accept"));
}
}
//添加后立即上传
setTimeout(function () {
up.start();
}, 1);
},
//上传进行中的回调
onUploadProgress: function (up, file) {
},
//上传之前的回调
onBeforeUpload: function (up, file) {
},
//初始化完成
onPostInit: function (up) {
},
//上传成功的回调
onUploadSuccess: function (up, ret) {
var button = up.settings.button;
var onUploadSuccess = up.settings.onUploadSuccess;
var data = typeof ret.data !== 'undefined' ? ret.data : null;
//上传成功后回调
if (button) {
//如果有文本框则填充
},
//文件添加成功后
onFileAdded: function (up, files) {
var button = up.settings.button;
$(button).data("bakup-html", $(button).html());
var maxcount = $(button).data("maxcount");
var input_id = $(button).data("input-id") ? $(button).data("input-id") : "";
if (input_id) {
var urlArr = [];
maxcount = typeof maxcount !== "undefined" ? maxcount : 0;
if (maxcount > 0 && input_id) {
var inputObj = $("#" + input_id);
if ($(button).data("multiple") && inputObj.val() !== "") {
urlArr.push(inputObj.val());
if (inputObj.size() > 0) {
var value = $.trim(inputObj.val());
var nums = value === '' ? 0 : value.split(/\,/).length;
var remains = maxcount - nums;
if (files.length > remains) {
for (var i = 0; i < files.length; i++) {
up.removeFile(files[i]);
}
Toastr.error(__('You can upload up to %d file%s', remains));
return false;
}
}
urlArr.push(data.url);
inputObj.val(urlArr.join(",")).trigger("change");
}
//如果有回调函数
var onDomUploadSuccess = $(button).data("upload-success");
if (onDomUploadSuccess) {
if (typeof onDomUploadSuccess !== 'function' && typeof Upload.api.custom[onDomUploadSuccess] === 'function') {
onDomUploadSuccess = Upload.api.custom[onDomUploadSuccess];
//添加后立即上传
setTimeout(function () {
up.start();
}, 1);
},
//上传进行中的回调
onUploadProgress: function (up, file) {
},
//上传之前的回调
onBeforeUpload: function (up, file) {
},
//上传成功的回调
onUploadSuccess: function (up, ret) {
var button = up.settings.button;
var onUploadSuccess = up.settings.onUploadSuccess;
var data = typeof ret.data !== 'undefined' ? ret.data : null;
//上传成功后回调
if (button) {
//如果有文本框则填充
var input_id = $(button).data("input-id") ? $(button).data("input-id") : "";
if (input_id) {
var urlArr = [];
var inputObj = $("#" + input_id);
if ($(button).data("multiple") && inputObj.val() !== "") {
urlArr.push(inputObj.val());
}
urlArr.push(data.url);
inputObj.val(urlArr.join(",")).trigger("change");
}
if (typeof onDomUploadSuccess === 'function') {
var result = onDomUploadSuccess.call(button, data, ret);
if (result === false)
return;
//如果有回调函数
var onDomUploadSuccess = $(button).data("upload-success");
if (onDomUploadSuccess) {
if (typeof onDomUploadSuccess !== 'function' && typeof Upload.api.custom[onDomUploadSuccess] === 'function') {
onDomUploadSuccess = Upload.api.custom[onDomUploadSuccess];
}
if (typeof onDomUploadSuccess === 'function') {
var result = onDomUploadSuccess.call(button, data, ret);
if (result === false)
return;
}
}
}
}
if (typeof onUploadSuccess === 'function') {
var result = onUploadSuccess.call(button, data, ret);
if (result === false)
return;
}
},
//上传错误的回调
onUploadError: function (up, ret) {
var button = up.settings.button;
var onUploadError = up.settings.onUploadError;
var data = typeof ret.data !== 'undefined' ? ret.data : null;
if (button) {
var onDomUploadError = $(button).data("upload-error");
if (onDomUploadError) {
if (typeof onDomUploadError !== 'function' && typeof Upload.api.custom[onDomUploadError] === 'function') {
onDomUploadError = Upload.api.custom[onDomUploadError];
}
if (typeof onDomUploadError === 'function') {
var result = onDomUploadError.call(button, data, ret);
if (result === false)
return;
if (typeof onUploadSuccess === 'function') {
var result = onUploadSuccess.call(button, data, ret);
if (result === false)
return;
}
},
//上传错误的回调
onUploadError: function (up, ret) {
var button = up.settings.button;
var onUploadError = up.settings.onUploadError;
var data = typeof ret.data !== 'undefined' ? ret.data : null;
if (button) {
var onDomUploadError = $(button).data("upload-error");
if (onDomUploadError) {
if (typeof onDomUploadError !== 'function' && typeof Upload.api.custom[onDomUploadError] === 'function') {
onDomUploadError = Upload.api.custom[onDomUploadError];
}
if (typeof onDomUploadError === 'function') {
var result = onDomUploadError.call(button, data, ret);
if (result === false)
return;
}
}
}
}
if (typeof onUploadError === 'function') {
var result = onUploadError.call(button, data, ret);
if (result === false) {
return;
}
}
Toastr.error(ret.msg + "(code:" + ret.code + ")");
},
//服务器响应数据后
onUploadResponse: function (response) {
try {
var ret = typeof response === 'object' ? response : JSON.parse(response);
if (!ret.hasOwnProperty('code')) {
$.extend(ret, {code: -2, msg: response, data: null});
if (typeof onUploadError === 'function') {
var result = onUploadError.call(button, data, ret);
if (result === false) {
return;
}
}
} catch (e) {
var ret = {code: -1, msg: e.message, data: null};
}
return ret;
},
//上传全部结束后
onUploadComplete: function (up, files) {
var button = up.settings.button;
var onUploadComplete = up.settings.onUploadComplete;
if (button) {
var onDomUploadComplete = $(button).data("upload-complete");
if (onDomUploadComplete) {
if (typeof onDomUploadComplete !== 'function' && typeof Upload.api.custom[onDomUploadComplete] === 'function') {
onDomUploadComplete = Upload.api.custom[onDomUploadComplete];
Toastr.error(ret.msg + "(code:" + ret.code + ")");
},
//服务器响应数据后
onUploadResponse: function (response) {
try {
var ret = typeof response === 'object' ? response : JSON.parse(response);
if (!ret.hasOwnProperty('code')) {
$.extend(ret, {code: -2, msg: response, data: null});
}
if (typeof onDomUploadComplete === 'function') {
var result = onDomUploadComplete.call(button, files);
if (result === false)
return;
} catch (e) {
var ret = {code: -1, msg: e.message, data: null};
}
return ret;
},
//上传全部结束后
onUploadComplete: function (up, files) {
var button = up.settings.button;
var onUploadComplete = up.settings.onUploadComplete;
if (button) {
var onDomUploadComplete = $(button).data("upload-complete");
if (onDomUploadComplete) {
if (typeof onDomUploadComplete !== 'function' && typeof Upload.api.custom[onDomUploadComplete] === 'function') {
onDomUploadComplete = Upload.api.custom[onDomUploadComplete];
}
if (typeof onDomUploadComplete === 'function') {
var result = onDomUploadComplete.call(button, files);
if (result === false)
return;
}
}
}
}
if (typeof onUploadComplete === 'function') {
var result = onUploadComplete.call(button, files);
if (result === false) {
return;
if (typeof onUploadComplete === 'function') {
var result = onUploadComplete.call(button, files);
if (result === false) {
return;
}
}
}
}
},
api: {
//Plupload上传
plupload: function (element, onUploadSuccess, onUploadError, onUploadComplete) {
element = typeof element === 'undefined' ? Upload.config.classname : element;
$(element, Upload.config.container).each(function () {
if ($(this).attr("initialized")) {
return true;
}
$(this).attr("initialized", true);
var that = this;
var id = $(this).prop("id");
var url = $(this).data("url");
var maxsize = $(this).data("maxsize");
var mimetype = $(this).data("mimetype");
var multipart = $(this).data("multipart");
var multiple = $(this).data("multiple");
},
api: {
//Plupload上传
plupload: function (element, onUploadSuccess, onUploadError, onUploadComplete) {
element = typeof element === 'undefined' ? Upload.config.classname : element;
$(element, Upload.config.container).each(function () {
if ($(this).attr("initialized")) {
return true;
}
$(this).attr("initialized", true);
var that = this;
var id = $(this).prop("id");
var url = $(this).data("url");
var maxsize = $(this).data("maxsize");
var mimetype = $(this).data("mimetype");
var multipart = $(this).data("multipart");
var multiple = $(this).data("multiple");
//填充ID
var input_id = $(that).data("input-id") ? $(that).data("input-id") : "";
//预览ID
var preview_id = $(that).data("preview-id") ? $(that).data("preview-id") : "";
//填充ID
var input_id = $(that).data("input-id") ? $(that).data("input-id") : "";
//预览ID
var preview_id = $(that).data("preview-id") ? $(that).data("preview-id") : "";
//上传URL
url = url ? url : Config.upload.uploadurl;
url = Fast.api.fixurl(url);
//最大可上传文件大小
maxsize = typeof maxsize !== "undefined" ? maxsize : Config.upload.maxsize;
//文件类型
mimetype = typeof mimetype !== "undefined" ? mimetype : Config.upload.mimetype;
//请求的表单参数
multipart = typeof multipart !== "undefined" ? multipart : Config.upload.multipart;
//是否支持批量上传
multiple = typeof multiple !== "undefined" ? multiple : Config.upload.multiple;
var mimetypeArr = new Array();
//支持后缀和Mimetype格式,以,分隔
if (mimetype && mimetype !== "*" && mimetype.indexOf("/") === -1) {
var tempArr = mimetype.split(',');
for (var i = 0; i < tempArr.length; i++) {
mimetypeArr.push({title: __('Files'), extensions: tempArr[i]});
//上传URL
url = url ? url : Config.upload.uploadurl;
url = Fast.api.fixurl(url);
//最大可上传文件大小
maxsize = typeof maxsize !== "undefined" ? maxsize : Config.upload.maxsize;
//文件类型
mimetype = typeof mimetype !== "undefined" ? mimetype : Config.upload.mimetype;
//请求的表单参数
multipart = typeof multipart !== "undefined" ? multipart : Config.upload.multipart;
//是否支持批量上传
multiple = typeof multiple !== "undefined" ? multiple : Config.upload.multiple;
var mimetypeArr = new Array();
//支持后缀和Mimetype格式,以,分隔
if (mimetype && mimetype !== "*" && mimetype.indexOf("/") === -1) {
var tempArr = mimetype.split(',');
for (var i = 0; i < tempArr.length; i++) {
mimetypeArr.push({title: __('Files'), extensions: tempArr[i]});
}
mimetype = mimetypeArr;
}
mimetype = mimetypeArr;
}
//生成Plupload实例
Upload.list[id] = new Plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
multi_selection: multiple, //是否允许多选批量上传
browse_button: id, // 浏览按钮的ID
container: $(this).parent().get(0), //取按钮的上级元素
flash_swf_url: '/assets/libs/plupload/js/Moxie.swf',
silverlight_xap_url: '/assets/libs/plupload/js/Moxie.xap',
drop_element: [id, $(this).data("input-id")],
filters: {
max_file_size: maxsize,
mime_types: mimetype,
},
url: url,
multipart_params: $.isArray(multipart) ? {} : multipart,
init: {
PostInit: Upload.events.onPostInit,
FilesAdded: Upload.events.onFileAdded,
BeforeUpload: Upload.events.onBeforeUpload,
UploadProgress: function (up, file) {
var button = up.settings.button;
$(button).prop("disabled", true).html("<i class='fa fa-upload'></i> " + __('Upload') + file.percent + "%");
Upload.events.onUploadProgress(up, file);
//生成Plupload实例
Upload.list[id] = new Plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
multi_selection: multiple, //是否允许多选批量上传
browse_button: id, // 浏览按钮的ID
container: $(this).parent().get(0), //取按钮的上级元素
flash_swf_url: '/assets/libs/plupload/js/Moxie.swf',
silverlight_xap_url: '/assets/libs/plupload/js/Moxie.xap',
drop_element: [id, $(this).data("input-id")],
filters: {
max_file_size: maxsize,
mime_types: mimetype,
},
FileUploaded: function (up, file, info) {
var button = up.settings.button;
//还原按钮文字及状态
$(button).prop("disabled", false).html($(button).data("bakup-html"));
var ret = Upload.events.onUploadResponse(info.response, info, up, file);
file.ret = ret;
if (ret.code === 1) {
Upload.events.onUploadSuccess(up, ret, file);
} else {
Upload.events.onUploadError(up, ret, file);
url: url,
multipart_params: $.isArray(multipart) ? {} : multipart,
init: {
PostInit: Upload.events.onPostInit,
FilesAdded: Upload.events.onFileAdded,
BeforeUpload: Upload.events.onBeforeUpload,
UploadProgress: function (up, file) {
var button = up.settings.button;
$(button).prop("disabled", true).html("<i class='fa fa-upload'></i> " + __('Upload') + file.percent + "%");
Upload.events.onUploadProgress(up, file);
},
FileUploaded: function (up, file, info) {
var button = up.settings.button;
//还原按钮文字及状态
$(button).prop("disabled", false).html($(button).data("bakup-html"));
var ret = Upload.events.onUploadResponse(info.response, info, up, file);
file.ret = ret;
if (ret.code === 1) {
Upload.events.onUploadSuccess(up, ret, file);
} else {
Upload.events.onUploadError(up, ret, file);
}
},
UploadComplete: Upload.events.onUploadComplete,
Error: function (up, err) {
var button = up.settings.button;
$(button).prop("disabled", false).html($(button).data("bakup-html"));
var ret = {code: err.code, msg: err.message, data: null};
Upload.events.onUploadError(up, ret);
}
},
UploadComplete: Upload.events.onUploadComplete,
Error: function (up, err) {
var button = up.settings.button;
$(button).prop("disabled", false).html($(button).data("bakup-html"));
var ret = {code: err.code, msg: err.message, data: null};
Upload.events.onUploadError(up, ret);
}
},
onUploadSuccess: onUploadSuccess,
onUploadError: onUploadError,
onUploadComplete: onUploadComplete,
button: that
});
onUploadSuccess: onUploadSuccess,
onUploadError: onUploadError,
onUploadComplete: onUploadComplete,
button: that
});
//拖动排序
if (preview_id && multiple) {
require(['dragsort'], function () {
$("#" + preview_id).dragsort({
dragSelector: "li a:not(.btn-trash)",
dragEnd: function () {
$("#" + preview_id).trigger("fa.preview.change");
},
placeHolderTemplate: '<li class="col-xs-3"></li>'
//拖动排序
if (preview_id && multiple) {
require(['dragsort'], function () {
$("#" + preview_id).dragsort({
dragSelector: "li a:not(.btn-trash)",
dragEnd: function () {
$("#" + preview_id).trigger("fa.preview.change");
},
placeHolderTemplate: '<li class="col-xs-3"></li>'
});
});
});
}
if (preview_id && input_id) {
$(document.body).on("keyup change", "#" + input_id, function () {
var inputStr = $("#" + input_id).val();
var inputArr = inputStr.split(/\,/);
$("#" + preview_id).empty();
var tpl = $("#" + preview_id).data("template") ? $("#" + preview_id).data("template") : "";
$.each(inputArr, function (i, j) {
if (!j) {
return true;
}
if (preview_id && input_id) {
$(document.body).on("keyup change", "#" + input_id, function () {
var inputStr = $("#" + input_id).val();
var inputArr = inputStr.split(/\,/);
$("#" + preview_id).empty();
var tpl = $("#" + preview_id).data("template") ? $("#" + preview_id).data("template") : "";
$.each(inputArr, function (i, j) {
if (!j) {
return true;
}
var data = {url: j, fullurl: Fast.api.cdnurl(j), data: $(that).data()};
var html = tpl ? Template(tpl, data) : Template.render(Upload.config.previewtpl, data);
$("#" + preview_id).append(html);
});
});
$("#" + input_id).trigger("change");
}
if (preview_id) {
// 监听事件
$(document.body).on("fa.preview.change", "#" + preview_id, function () {
var urlArr = new Array();
$("#" + preview_id + " [data-url]").each(function (i, j) {
urlArr.push($(this).data("url"));
});
if (input_id) {
$("#" + input_id).val(urlArr.join(","));
}
var data = {url: j, fullurl: Fast.api.cdnurl(j), data: $(that).data()};
var html = tpl ? Template(tpl, data) : Template.render(Upload.config.previewtpl, data);
$("#" + preview_id).append(html);
});
});
$("#" + input_id).trigger("change");
}
if (preview_id) {
// 监听事件
$(document.body).on("fa.preview.change", "#" + preview_id, function () {
var urlArr = new Array();
$("#" + preview_id + " [data-url]").each(function (i, j) {
urlArr.push($(this).data("url"));
// 移除按钮事件
$(document.body).on("click", "#" + preview_id + " .btn-trash", function () {
$(this).closest("li").remove();
$("#" + preview_id).trigger("fa.preview.change");
});
if (input_id) {
$("#" + input_id).val(urlArr.join(","));
}
});
// 移除按钮事件
$(document.body).on("click", "#" + preview_id + " .btn-trash", function () {
$(this).closest("li").remove();
$("#" + preview_id).trigger("fa.preview.change");
});
}
if (input_id) {
//粘贴上传
$("body").on('paste', "#" + input_id, function (event) {
var that = this;
var image, pasteEvent;
pasteEvent = event.originalEvent;
if (pasteEvent.clipboardData && pasteEvent.clipboardData.items) {
image = Upload.api.getImageFromClipboard(pasteEvent);
if (image) {
event.preventDefault();
var button = $(".plupload[data-input-id='" + $(that).attr("id") + "']");
Upload.api.send(image, function (data) {
var urlArr = [];
if (button && button.data("multiple") && $(that).val() !== '') {
urlArr.push($(that).val());
}
urlArr.push(data.url);
$(that).val(urlArr.join(",")).trigger("change");
});
}
}
});
//拖拽上传
$("body").on('drop', "#" + input_id, function (event) {
var that = this;
var images, pasteEvent;
pasteEvent = event.originalEvent;
if (pasteEvent.dataTransfer && pasteEvent.dataTransfer.files) {
images = Upload.api.getImageFromDrop(pasteEvent);
if (images.length > 0) {
event.preventDefault();
var button = $(".plupload[data-input-id='" + $(that).attr("id") + "']");
$.each(images, function (i, image) {
Upload.api.send(image, function (data) {
var urlArr = [];
if (button && button.data("multiple") && $(that).val() !== '') {
urlArr.push($(that).val());
}
urlArr.push(data.url);
$(that).val(urlArr.join(",")).trigger("change");
});
});
}
}
});
}
Upload.list[id].init();
});
},
// AJAX异步上传
send: function (file, onUploadSuccess, onUploadError, onUploadComplete) {
var index = Layer.msg(__('Uploading'), {offset: 't', time: 0});
var id = Plupload.guid();
var _onPostInit = Upload.events.onPostInit;
Upload.events.onPostInit = function () {
// 当加载完成后添加文件并上传
Upload.list[id].addFile(file);
//Upload.list[id].start();
};
$('<button type="button" id="' + id + '" class="btn btn-danger hidden plupload" />').appendTo("body");
$("#" + id).data("upload-complete", function (files) {
Upload.events.onPostInit = _onPostInit;
Layer.close(index);
});
Upload.api.plupload("#" + id, onUploadSuccess, onUploadError, onUploadComplete);
},
custom: {
//自定义上传完成回调
afteruploadcallback: function (response) {
console.log(this, response);
alert("Custom Callback,Response URL:" + response.url);
},
},
getImageFromClipboard: function (data) {
var i, item;
i = 0;
while (i < data.clipboardData.items.length) {
item = data.clipboardData.items[i];
if (item.type.indexOf("image") !== -1) {
return item.getAsFile() || false;
}
i++;
}
Upload.list[id].init();
});
},
// AJAX异步上传
send: function (file, onUploadSuccess, onUploadError, onUploadComplete) {
var index = Layer.msg(__('Uploading'), {offset: 't', time: 0});
var id = Plupload.guid();
var _onPostInit = Upload.events.onPostInit;
Upload.events.onPostInit = function () {
// 当加载完成后添加文件并上传
Upload.list[id].addFile(file);
//Upload.list[id].start();
};
$('<button type="button" id="' + id + '" class="btn btn-danger hidden plupload" />').appendTo("body");
$("#" + id).data("upload-complete", function (files) {
Upload.events.onPostInit = _onPostInit;
Layer.close(index);
});
Upload.api.plupload("#" + id, onUploadSuccess, onUploadError, onUploadComplete);
},
custom: {
//自定义上传完成回调
afteruploadcallback: function (response) {
console.log(this, response);
alert("Custom Callback,Response URL:" + response.url);
return false;
},
},
getImageFromDrop: function (data) {
var i, item, images;
i = 0;
images = [];
while (i < data.dataTransfer.files.length) {
item = data.dataTransfer.files[i];
if (item.type.indexOf("image") !== -1) {
images.push(item);
}
i++;
}
return images;
}
}
}
};
;
return Upload;
});
\ No newline at end of file
... ...