Commit a2758e4e6734fe442fbbbc474527b591086af21c

Authored by yangfei
1 parent 670f95bd3d
Exists in master

内容管理前端页面

Showing 34 changed files with 3845 additions and 1733 deletions

parent/base.common/src/main/java/com/lyms/base/common/dao/content/ContentCategoriesMapper.java View file @ a2758e4
1 1 package com.lyms.base.common.dao.content;
2 2  
3 3 import com.baomidou.mybatisplus.mapper.BaseMapper;
  4 +import com.baomidou.mybatisplus.plugins.Page;
4 5 import com.lyms.base.common.entity.content.ContentCategories;
5 6 import org.springframework.stereotype.Repository;
6 7  
7 8 import java.io.Serializable;
  9 +import java.util.List;
  10 +
8 11 /**
9 12 * <p>
10 13 * Mapper接口
... ... @@ -18,5 +21,6 @@
18 21  
19 22 public Integer deleteLogicById(Serializable id);
20 23  
  24 + List<ContentCategories> getCategories(Page<ContentCategories> page, String name);
21 25 }
parent/base.common/src/main/java/com/lyms/base/common/dao/content/ContentCategoriesMapper.xml View file @ a2758e4
... ... @@ -24,5 +24,16 @@
24 24 <sql id="Base_Column_List">
25 25 ID AS id, NAME AS name, ICON AS icon, DESCRIPTION AS description, LEVEL AS level, PERENT AS perent, CREATE_TIME AS createTime, CREATE_ID AS createId, CREATE_NAME AS createName, MODIFY_ID AS modifyId, MODIFY_NAME AS modifyName, MODIFY_TIME AS modifyTime, IFDEL AS ifdel, ENABLE AS enable
26 26 </sql>
  27 +
  28 + <select id="getCategories" resultMap="BaseResultMap">
  29 + select ID,DESCRIPTION,`NAME`,`LEVEL`,PERENT from CONTENT_CATEGORIES
  30 + <where>
  31 + <if test="name!=null">
  32 + and `NAME` = #{name}
  33 + </if>
  34 + </where>
  35 +
  36 + </select>
  37 +
27 38 </mapper>
parent/base.common/src/main/java/com/lyms/base/common/dao/content/ContentTagsMapper.java View file @ a2758e4
1 1 package com.lyms.base.common.dao.content;
2 2  
3 3 import com.baomidou.mybatisplus.mapper.BaseMapper;
  4 +import com.baomidou.mybatisplus.plugins.Page;
4 5 import com.lyms.base.common.entity.content.ContentTags;
5 6 import org.springframework.stereotype.Repository;
6 7  
7 8 import java.io.Serializable;
  9 +import java.util.List;
  10 +
8 11 /**
9 12 * <p>
10 13 * Mapper接口
... ... @@ -18,5 +21,6 @@
18 21  
19 22 public Integer deleteLogicById(Serializable id);
20 23  
  24 + public List<ContentTags> getTags(Page<ContentTags> page, String name);
21 25 }
parent/base.common/src/main/java/com/lyms/base/common/dao/content/ContentTagsMapper.xml View file @ a2758e4
... ... @@ -23,5 +23,14 @@
23 23 <sql id="Base_Column_List">
24 24 ID AS id, TAG_NAME AS tagName, TAG_DESC AS tagDesc, LEVEL AS level, PERENT_ID AS perentId, CREATE_TIME AS createTime, CREATE_ID AS createId, CREATE_NAME AS createName, MODIFY_ID AS modifyId, MODIFY_NAME AS modifyName, MODIFY_TIME AS modifyTime, IFDEL AS ifdel, ENABLE AS enable
25 25 </sql>
  26 +
  27 + <select id="getTags" resultMap="BaseResultMap">
  28 + select ID,TAG_NAME,TAG_DESC,`LEVEL`,PERENT_ID from CONTENT_TAGS
  29 + <where>
  30 + <if test="name!=null">
  31 + and `TAG_NAME` = #{name}
  32 + </if>
  33 + </where>
  34 + </select>
26 35 </mapper>
parent/base.common/src/main/java/com/lyms/base/common/service/content/ContentCategoriesService.java View file @ a2758e4
1 1 package com.lyms.base.common.service.content;
2 2  
  3 +import com.baomidou.mybatisplus.plugins.Page;
3 4 import com.lyms.base.common.entity.content.ContentCategories;
4 5 import com.lyms.web.service.BaseService;
5 6  
... ... @@ -21,6 +22,7 @@
21 22 * <li>@return 大于0修改成功,否则为失败
22 23 */
23 24 public Integer deleteLogicById(Serializable id);
24   -
  25 +
  26 + Page<ContentCategories> getCategories(Page<ContentCategories> page, String name);
25 27 }
parent/base.common/src/main/java/com/lyms/base/common/service/content/ContentTagsService.java View file @ a2758e4
1 1 package com.lyms.base.common.service.content;
2 2  
  3 +import com.baomidou.mybatisplus.plugins.Page;
3 4 import com.lyms.base.common.entity.content.ContentTags;
4 5 import com.lyms.web.service.BaseService;
5 6  
... ... @@ -21,6 +22,7 @@
21 22 * <li>@return 大于0修改成功,否则为失败
22 23 */
23 24 public Integer deleteLogicById(Serializable id);
24   -
  25 +
  26 + public Page<ContentTags> getTags(Page<ContentTags> page, String name);
25 27 }
parent/base.common/src/main/java/com/lyms/base/common/service/content/impl/ContentCategoriesServiceImpl.java View file @ a2758e4
1 1 package com.lyms.base.common.service.content.impl;
2 2  
  3 +import com.baomidou.mybatisplus.plugins.Page;
3 4 import com.baomidou.mybatisplus.service.impl.ServiceImpl;
4 5 import com.lyms.base.common.dao.content.ContentCategoriesMapper;
5 6 import com.lyms.base.common.entity.content.ContentCategories;
... ... @@ -7,6 +8,7 @@
7 8 import org.springframework.stereotype.Service;
8 9  
9 10 import java.io.Serializable;
  11 +import java.util.List;
10 12  
11 13 /**
12 14 * <p>
... ... @@ -21,6 +23,13 @@
21 23  
22 24 public Integer deleteLogicById(Serializable id){
23 25 return baseMapper.deleteLogicById(id);
  26 + }
  27 +
  28 + @Override
  29 + public Page<ContentCategories> getCategories(Page<ContentCategories> page, String name) {
  30 + List<ContentCategories> lists = baseMapper.getCategories(page, name);
  31 + page.setRecords(lists);
  32 + return page;
24 33 }
25 34 }
parent/base.common/src/main/java/com/lyms/base/common/service/content/impl/ContentTagsServiceImpl.java View file @ a2758e4
1 1 package com.lyms.base.common.service.content.impl;
2 2  
  3 +import com.baomidou.mybatisplus.plugins.Page;
3 4 import com.baomidou.mybatisplus.service.impl.ServiceImpl;
4 5 import com.lyms.base.common.dao.content.ContentTagsMapper;
5 6 import com.lyms.base.common.entity.content.ContentTags;
... ... @@ -7,6 +8,7 @@
7 8 import org.springframework.stereotype.Service;
8 9  
9 10 import java.io.Serializable;
  11 +import java.util.List;
10 12  
11 13 /**
12 14 * <p>
... ... @@ -21,6 +23,13 @@
21 23  
22 24 public Integer deleteLogicById(Serializable id){
23 25 return baseMapper.deleteLogicById(id);
  26 + }
  27 +
  28 + @Override
  29 + public Page<ContentTags> getTags(Page<ContentTags> page, String name) {
  30 + List<ContentTags> lists = baseMapper.getTags(page, name);
  31 + page.setRecords(lists);
  32 + return page;
24 33 }
25 34 }
parent/center.manager/src/main/java/com/lyms/cm/controller/content/ContentArticlesController.java View file @ a2758e4
... ... @@ -18,13 +18,23 @@
18 18 public class ContentArticlesController extends BaseController {
19 19  
20 20 /**
21   - * 跳转到列表页面
  21 + * 跳转到新增页面
22 22 *
23 23 * @return
24 24 */
25 25 @RequestMapping(value = "/toEdit", method = { RequestMethod.GET })
26   - public String toList() {
  26 + public String toEdit() {
27 27 return "/articles/articles_edit";
  28 + }
  29 +
  30 + /**
  31 + * 跳转到列表页面
  32 + *
  33 + * @return
  34 + */
  35 + @RequestMapping(value = "/toList", method = { RequestMethod.GET })
  36 + public String toList() {
  37 + return "/articles/articles_list";
28 38 }
29 39  
30 40 }
parent/center.manager/src/main/java/com/lyms/cm/controller/content/ContentArticlesTagsController.java View file @ a2758e4
... ... @@ -15,6 +15,6 @@
15 15 @Controller
16 16 @RequestMapping("/contentArticlesTags")
17 17 public class ContentArticlesTagsController extends BaseController {
18   -
  18 +
19 19 }
parent/center.manager/src/main/java/com/lyms/cm/controller/content/ContentCategoriesController.java View file @ a2758e4
1 1 package com.lyms.cm.controller.content;
2 2  
3   -import java.util.List;
4   -
  3 +import com.baomidou.mybatisplus.plugins.Page;
  4 +import com.lyms.base.common.entity.content.ContentCategories;
  5 +import com.lyms.base.common.service.content.ContentCategoriesService;
  6 +import com.lyms.util.StrUtils;
  7 +import com.lyms.web.bean.AjaxResult;
  8 +import com.lyms.web.controller.BaseController;
5 9 import org.springframework.beans.factory.annotation.Autowired;
6 10 import org.springframework.stereotype.Controller;
7 11 import org.springframework.web.bind.annotation.RequestMapping;
8 12 import org.springframework.web.bind.annotation.RequestMethod;
  13 +import org.springframework.web.bind.annotation.RequestParam;
9 14 import org.springframework.web.bind.annotation.ResponseBody;
10 15  
11   -import com.lyms.base.common.entity.content.ContentCategories;
12   -import com.lyms.base.common.service.content.ContentCategoriesService;
13   -import com.lyms.web.bean.AjaxResult;
14   -import com.lyms.web.controller.BaseController;
  16 +import java.util.List;
  17 +import java.util.Map;
15 18  
16 19 /**
17 20 * <p>
18 21  
19 22  
... ... @@ -27,15 +30,51 @@
27 30 @Autowired
28 31 public ContentCategoriesService categorService;
29 32 /**
30   - * 获取消息内容列表
31   - * @param verId
  33 + * 新增图文获取栏目列表
32 34 * @return
33 35 */
34 36 @ResponseBody
35   - @RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
36   - public AjaxResult list() {
  37 + @RequestMapping(value = "/selelist", method = { RequestMethod.GET, RequestMethod.POST })
  38 + public AjaxResult selelist() {
37 39 List<ContentCategories> lists = categorService.selectList(null);
38 40 return AjaxResult.returnSuccess(lists);
39 41 }
  42 +
  43 + /**
  44 + * 获取栏目列表
  45 + * @param name 栏目名称
  46 + * @return
  47 + */
  48 + @ResponseBody
  49 + @RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
  50 + public Map<String, Object> list(@RequestParam(defaultValue= "",value="name",required = false) String name) {
  51 + Page<ContentCategories> page = getPage();
  52 + if(StrUtils.isNotEmpty(name)){
  53 + page = categorService.getCategories(page,name);
  54 + }else{
  55 + page = categorService.getCategories(page,null);
  56 + }
  57 + return toGridData(page);
  58 + }
  59 +
  60 + /**
  61 + * 跳转到新增页面
  62 + *
  63 + * @return
  64 + */
  65 + @RequestMapping(value = "/toEdit", method = { RequestMethod.GET })
  66 + public String toEdit() {
  67 + return "/categories/categonies_edit";
  68 + }
  69 +
  70 + /**
  71 + * 跳转到列表页面
  72 + *
  73 + * @return
  74 + */
  75 + @RequestMapping(value = "/toList", method = { RequestMethod.GET })
  76 + public String toList() {
  77 + return "/categories/categonies_list";
  78 + }
40 79 }
parent/center.manager/src/main/java/com/lyms/cm/controller/content/ContentTagsController.java View file @ a2758e4
1 1 package com.lyms.cm.controller.content;
2 2  
3   -import java.util.List;
4   -import java.util.Map;
5   -
  3 +import com.baomidou.mybatisplus.plugins.Page;
  4 +import com.lyms.base.common.entity.content.ContentTags;
  5 +import com.lyms.base.common.service.content.ContentTagsService;
  6 +import com.lyms.util.StrUtils;
  7 +import com.lyms.web.bean.AjaxResult;
  8 +import com.lyms.web.controller.BaseController;
6 9 import org.springframework.beans.factory.annotation.Autowired;
7 10 import org.springframework.stereotype.Controller;
8 11 import org.springframework.web.bind.annotation.RequestMapping;
... ... @@ -10,12 +13,8 @@
10 13 import org.springframework.web.bind.annotation.RequestParam;
11 14 import org.springframework.web.bind.annotation.ResponseBody;
12 15  
13   -import com.baomidou.mybatisplus.plugins.Page;
14   -import com.lyms.base.common.entity.content.ContentTags;
15   -import com.lyms.base.common.service.content.ContentTagsService;
16   -import com.lyms.util.StrUtils;
17   -import com.lyms.web.bean.AjaxResult;
18   -import com.lyms.web.controller.BaseController;
  16 +import java.util.List;
  17 +import java.util.Map;
19 18  
20 19 /**
21 20 * <p>
22 21  
... ... @@ -30,12 +29,49 @@
30 29 public class ContentTagsController extends BaseController {
31 30 @Autowired
32 31 private ContentTagsService contentTagsService;
33   -
34   - @ResponseBody
35   - @RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
36   - public AjaxResult list() {
  32 +
  33 + /**
  34 + * 跳转到列表页面
  35 + *
  36 + * @return
  37 + */
  38 + @RequestMapping(value = "/toList", method = { RequestMethod.GET })
  39 + public String toList() {
  40 + return "/tags/tags_list";
  41 + }
  42 +
  43 + /**
  44 + * 跳转到新增页面
  45 + *
  46 + * @return
  47 + */
  48 + @RequestMapping(value = "/toEdit", method = { RequestMethod.GET })
  49 + public String toEdit() {
  50 + return "/tags/tags_edit";
  51 + }
  52 +
  53 +
  54 + @ResponseBody
  55 + @RequestMapping(value = "/seleList", method = { RequestMethod.GET, RequestMethod.POST })
  56 + public AjaxResult seleList() {
37 57 List<ContentTags> lists = contentTagsService.selectList(null);
38 58 return AjaxResult.returnSuccess(lists);
  59 + }
  60 + /**
  61 + * 获取栏目列表
  62 + * @param name 栏目名称
  63 + * @return
  64 + */
  65 + @ResponseBody
  66 + @RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
  67 + public Map<String, Object> list(@RequestParam(defaultValue= "",value="name",required = false) String name) {
  68 + Page<ContentTags> page = getPage();
  69 + if(StrUtils.isNotEmpty(name)){
  70 + page = contentTagsService.getTags(page,name);
  71 + }else{
  72 + page = contentTagsService.getTags(page,null);
  73 + }
  74 + return toGridData(page);
39 75 }
40 76 }
parent/center.manager/src/main/java/com/lyms/cm/controller/content/UeditorContoller.java View file @ a2758e4
1 1 package com.lyms.cm.controller.content;
2 2  
3   -import java.io.IOException;
4   -
5   -import javax.servlet.http.HttpServletRequest;
6   -import javax.servlet.http.HttpServletResponse;
7   -
  3 +import com.lyms.cm.qiniu.AuthException;
  4 +import com.lyms.cm.qiniu.Base64Coder;
  5 +import com.lyms.cm.qiniu.Config;
  6 +import com.lyms.cm.qiniu.Uptoken;
  7 +import com.qiniu.util.Auth;
8 8 import org.json.JSONException;
9 9 import org.json.JSONObject;
10 10 import org.springframework.stereotype.Controller;
11 11  
... ... @@ -12,16 +12,15 @@
12 12 import org.springframework.web.bind.annotation.RequestMethod;
13 13 import org.springframework.web.bind.annotation.RequestParam;
14 14  
15   -import com.lyms.cm.qiniu.AuthException;
16   -import com.lyms.cm.qiniu.Base64Coder;
17   -import com.lyms.cm.qiniu.Uptoken;
  15 +import javax.servlet.http.HttpServletRequest;
  16 +import javax.servlet.http.HttpServletResponse;
  17 +import java.io.IOException;
18 18  
19 19 @Controller
20 20 @RequestMapping("/ueditor")
21 21 public class UeditorContoller {
22 22 /**
23 23 * 获取消息内容列表
24   - * @param verId
25 24 * @return
26 25 * @throws JSONException
27 26 * @throws IOException
... ... @@ -45,7 +44,6 @@
45 44  
46 45 /**
47 46 * 获取token
48   - * @param verId
49 47 * @return
50 48 * @throws JSONException
51 49 * @throws IOException
... ... @@ -60,5 +58,26 @@
60 58 json.append("token", Uptoken.makeUptoken(request));
61 59 response.getWriter().print(json.toString());
62 60 }
  61 +
  62 + /**
  63 + * 获取token
  64 + * @return
  65 + * @throws JSONException
  66 + * @throws IOException
  67 + * @throws AuthException
  68 + */
  69 + @RequestMapping(value = "/uploadGetToken", method = { RequestMethod.GET, RequestMethod.POST })
  70 + public void uploadGetToken(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, AuthException {
  71 + request.setCharacterEncoding("utf-8");
  72 + response.setCharacterEncoding("utf-8");
  73 + response.setContentType("application/json");
  74 + Auth auth = Auth.create(Config.ACCESS_KEY, Config.SECRET_KEY);
  75 + String upToken = auth.uploadToken(Config.BUCKET_NAME);
  76 + JSONObject job = new JSONObject();
  77 + job.put("uptoken",upToken);
  78 + System.out.println("jsonToken:"+job.toString());
  79 + response.getWriter().print(job.toString());
  80 + }
  81 +
63 82 }
parent/center.manager/src/main/java/com/lyms/cm/qiniu/Config.java View file @ a2758e4
... ... @@ -9,11 +9,9 @@
9 9  
10 10 public static String SECRET_KEY = "xLD30JhNUkoNNafRL3U4ncMzoOJwSj1EaXAUY-si";
11 11  
12   - public static String RS_HOST = "http://rs.qbox.me";
13   -
14   - public static String UP_HOST = "http://up.qbox.me";
15   -
16 12 public static String RSF_HOST = "http://rsf.qbox.me";
  13 +
  14 + public static String BUCKET_NAME = "mommybaby";
17 15  
18 16 }
parent/center.manager/src/main/java/com/lyms/cm/qiniu/Uptoken.java View file @ a2758e4
1 1 package com.lyms.cm.qiniu;
2 2  
3   -import java.util.UUID;
  3 +import org.json.JSONException;
4 4  
5 5 import javax.servlet.http.HttpServletRequest;
  6 +import java.util.UUID;
6 7  
7   -import org.json.JSONException;
8   -
9 8 public class Uptoken {
10 9  
11 10 public final static String makeUptoken(HttpServletRequest request) throws AuthException,
12 11 JSONException {
13 12 // System.out.println("请求路径:"+requestURL);
14 13 Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
15   - String bucketName = "mommybaby";
  14 + String bucketName = Config.BUCKET_NAME;
16 15 PutPolicy putPolicy = new PutPolicy(bucketName);
17 16 // 可以根据自己需要设置过期时间,sdk默认有设置,具体看源码
18 17 // putPolicy.expires = getDeadLine();
parent/center.manager/src/main/resources/rebel.xml View file @ a2758e4
1 1 <?xml version="1.0" encoding="UTF-8"?>
2   -<application generated-by="eclipse" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com" xsi:schemaLocation="http://www.zeroturnaround.com http://update.zeroturnaround.com/jrebel/rebel-2_1.xsd">
  2 +<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com" xsi:schemaLocation="http://www.zeroturnaround.com http://www.zeroturnaround.com/alderaan/rebel-2_0.xsd">
3 3  
4 4 <classpath>
5 5 <dir name="D:/lyms_wrok/parent/parent/center.manager/target/classes">
... ... @@ -7,11 +7,6 @@
7 7 </classpath>
8 8  
9 9 <web>
10   - <link target="/">
11   - <dir name="D:/lyms_wrok/parent/parent/center.manager/target/m2e-wtp/web-resources">
12   - <exclude name="/"/>
13   - </dir>
14   - </link>
15 10 <link target="/">
16 11 <dir name="D:/lyms_wrok/parent/parent/center.manager/src/main/webapp">
17 12 </dir>
parent/center.manager/src/main/webapp/WEB-INF/static/js/plugins/qiniu/formdata.js View file @ a2758e4
  1 +// jQuery zepto vue angular 等库皆有 progress 的实现 以jQuery为例:
  2 +$(function(){
  3 + var $key = $('#key'); // file name eg: the file is image.jpg,but $key='a.jpg', you will upload the file named 'a.jpg'
  4 + var $userfile = $('#userfile'); // the file you selected
  5 +
  6 + // upload info
  7 + var $selectedFile = $('.selected-file');
  8 + var $progress = $(".progress");
  9 + var $uploadedResult = $('.uploaded-result');
  10 +
  11 + $("#userfile").change(function() { // you can ues 'onchange' here to uplpad automatically after select a file
  12 + $uploadedResult.html('');
  13 + var selectedFile = $userfile.val();
  14 + if (selectedFile) {
  15 + // randomly generate the final file name
  16 + var ramdomName = Math.random().toString(36).substr(2) + $userfile.val().match(/\.?[^.\/]+$/);
  17 + $key.val(ramdomName);
  18 + $selectedFile.html('文件:' + selectedFile);
  19 + } else {
  20 + return false;
  21 + }
  22 + var f = new FormData(document.getElementById("testform"));
  23 + $.ajax({
  24 + url: 'http://upload.qiniu.com/', // Different bucket zone has different upload url, you can get right url by the browser error massage when uploading a file with wrong upload url.
  25 + type: 'POST',
  26 + data: f,
  27 + processData: false,
  28 + contentType: false,
  29 + xhr: function(){
  30 + myXhr = $.ajaxSettings.xhr();
  31 + if(myXhr.upload){
  32 + myXhr.upload.addEventListener('progress',function(e) {
  33 + // console.log(e);
  34 + if (e.lengthComputable) {
  35 + var percent = e.loaded/e.total*100;
  36 + $progress.html('上传:' + e.loaded + "/" + e.total+" bytes. " + percent.toFixed(2) + "%");
  37 + }
  38 + }, false);
  39 + }
  40 + return myXhr;
  41 + },
  42 + success: function(res) {
  43 + console.log("成功:" + JSON.stringify(res));
  44 + var str = '<span>已上传:' + res.key + '</span>';
  45 + if (res.key && res.key.match(/\.(jpg|jpeg|png|gif)$/)) {
  46 + str += '<img src="' + domain + res.key + '"/>';
  47 + }
  48 + $uploadedResult.html(str);
  49 + },
  50 + error: function(res) {
  51 + console.log("失败:" + JSON.stringify(res));
  52 + $uploadedResult.html('上传失败:' + res.responseText);
  53 + }
  54 + });
  55 + return false;
  56 + });
  57 +});
parent/center.manager/src/main/webapp/WEB-INF/static/js/plugins/qiniu/highlight.js View file @ a2758e4
  1 +var hljs=new function(){function l(o){return o.replace(/&/gm,"&amp;").replace(/</gm,"&lt;").replace(/>/gm,"&gt;")}function b(p){for(var o=p.firstChild;o;o=o.nextSibling){if(o.nodeName=="CODE"){return o}if(!(o.nodeType==3&&o.nodeValue.match(/\s+/))){break}}}function h(p,o){return Array.prototype.map.call(p.childNodes,function(q){if(q.nodeType==3){return o?q.nodeValue.replace(/\n/g,""):q.nodeValue}if(q.nodeName=="BR"){return"\n"}return h(q,o)}).join("")}function a(q){var p=(q.className+" "+q.parentNode.className).split(/\s+/);p=p.map(function(r){return r.replace(/^language-/,"")});for(var o=0;o<p.length;o++){if(e[p[o]]||p[o]=="no-highlight"){return p[o]}}}function c(q){var o=[];(function p(r,s){for(var t=r.firstChild;t;t=t.nextSibling){if(t.nodeType==3){s+=t.nodeValue.length}else{if(t.nodeName=="BR"){s+=1}else{if(t.nodeType==1){o.push({event:"start",offset:s,node:t});s=p(t,s);o.push({event:"stop",offset:s,node:t})}}}}return s})(q,0);return o}function j(x,v,w){var p=0;var y="";var r=[];function t(){if(x.length&&v.length){if(x[0].offset!=v[0].offset){return(x[0].offset<v[0].offset)?x:v}else{return v[0].event=="start"?x:v}}else{return x.length?x:v}}function s(A){function z(B){return" "+B.nodeName+'="'+l(B.value)+'"'}return"<"+A.nodeName+Array.prototype.map.call(A.attributes,z).join("")+">"}while(x.length||v.length){var u=t().splice(0,1)[0];y+=l(w.substr(p,u.offset-p));p=u.offset;if(u.event=="start"){y+=s(u.node);r.push(u.node)}else{if(u.event=="stop"){var o,q=r.length;do{q--;o=r[q];y+=("</"+o.nodeName.toLowerCase()+">")}while(o!=u.node);r.splice(q,1);while(q<r.length){y+=s(r[q]);q++}}}}return y+l(w.substr(p))}function f(q){function o(s,r){return RegExp(s,"m"+(q.cI?"i":"")+(r?"g":""))}function p(y,w){if(y.compiled){return}y.compiled=true;var s=[];if(y.k){var r={};function z(A,t){t.split(" ").forEach(function(B){var C=B.split("|");r[C[0]]=[A,C[1]?Number(C[1]):1];s.push(C[0])})}y.lR=o(y.l||hljs.IR,true);if(typeof y.k=="string"){z("keyword",y.k)}else{for(var x in y.k){if(!y.k.hasOwnProperty(x)){continue}z(x,y.k[x])}}y.k=r}if(w){if(y.bWK){y.b="\\b("+s.join("|")+")\\s"}y.bR=o(y.b?y.b:"\\B|\\b");if(!y.e&&!y.eW){y.e="\\B|\\b"}if(y.e){y.eR=o(y.e)}y.tE=y.e||"";if(y.eW&&w.tE){y.tE+=(y.e?"|":"")+w.tE}}if(y.i){y.iR=o(y.i)}if(y.r===undefined){y.r=1}if(!y.c){y.c=[]}for(var v=0;v<y.c.length;v++){if(y.c[v]=="self"){y.c[v]=y}p(y.c[v],y)}if(y.starts){p(y.starts,w)}var u=[];for(var v=0;v<y.c.length;v++){u.push(y.c[v].b)}if(y.tE){u.push(y.tE)}if(y.i){u.push(y.i)}y.t=u.length?o(u.join("|"),true):{exec:function(t){return null}}}p(q)}function d(D,E){function o(r,M){for(var L=0;L<M.c.length;L++){var K=M.c[L].bR.exec(r);if(K&&K.index==0){return M.c[L]}}}function s(K,r){if(K.e&&K.eR.test(r)){return K}if(K.eW){return s(K.parent,r)}}function t(r,K){return K.i&&K.iR.test(r)}function y(L,r){var K=F.cI?r[0].toLowerCase():r[0];return L.k.hasOwnProperty(K)&&L.k[K]}function G(){var K=l(w);if(!A.k){return K}var r="";var N=0;A.lR.lastIndex=0;var L=A.lR.exec(K);while(L){r+=K.substr(N,L.index-N);var M=y(A,L);if(M){v+=M[1];r+='<span class="'+M[0]+'">'+L[0]+"</span>"}else{r+=L[0]}N=A.lR.lastIndex;L=A.lR.exec(K)}return r+K.substr(N)}function z(){if(A.sL&&!e[A.sL]){return l(w)}var r=A.sL?d(A.sL,w):g(w);if(A.r>0){v+=r.keyword_count;B+=r.r}return'<span class="'+r.language+'">'+r.value+"</span>"}function J(){return A.sL!==undefined?z():G()}function I(L,r){var K=L.cN?'<span class="'+L.cN+'">':"";if(L.rB){x+=K;w=""}else{if(L.eB){x+=l(r)+K;w=""}else{x+=K;w=r}}A=Object.create(L,{parent:{value:A}});B+=L.r}function C(K,r){w+=K;if(r===undefined){x+=J();return 0}var L=o(r,A);if(L){x+=J();I(L,r);return L.rB?0:r.length}var M=s(A,r);if(M){if(!(M.rE||M.eE)){w+=r}x+=J();do{if(A.cN){x+="</span>"}A=A.parent}while(A!=M.parent);if(M.eE){x+=l(r)}w="";if(M.starts){I(M.starts,"")}return M.rE?0:r.length}if(t(r,A)){throw"Illegal"}w+=r;return r.length||1}var F=e[D];f(F);var A=F;var w="";var B=0;var v=0;var x="";try{var u,q,p=0;while(true){A.t.lastIndex=p;u=A.t.exec(E);if(!u){break}q=C(E.substr(p,u.index-p),u[0]);p=u.index+q}C(E.substr(p));return{r:B,keyword_count:v,value:x,language:D}}catch(H){if(H=="Illegal"){return{r:0,keyword_count:0,value:l(E)}}else{throw H}}}function g(s){var o={keyword_count:0,r:0,value:l(s)};var q=o;for(var p in e){if(!e.hasOwnProperty(p)){continue}var r=d(p,s);r.language=p;if(r.keyword_count+r.r>q.keyword_count+q.r){q=r}if(r.keyword_count+r.r>o.keyword_count+o.r){q=o;o=r}}if(q.language){o.second_best=q}return o}function i(q,p,o){if(p){q=q.replace(/^((<[^>]+>|\t)+)/gm,function(r,v,u,t){return v.replace(/\t/g,p)})}if(o){q=q.replace(/\n/g,"<br>")}return q}function m(r,u,p){var v=h(r,p);var t=a(r);if(t=="no-highlight"){return}var w=t?d(t,v):g(v);t=w.language;var o=c(r);if(o.length){var q=document.createElement("pre");q.innerHTML=w.value;w.value=j(o,c(q),v)}w.value=i(w.value,u,p);var s=r.className;if(!s.match("(\\s|^)(language-)?"+t+"(\\s|$)")){s=s?(s+" "+t):t}r.innerHTML=w.value;r.className=s;r.result={language:t,kw:w.keyword_count,re:w.r};if(w.second_best){r.second_best={language:w.second_best.language,kw:w.second_best.keyword_count,re:w.second_best.r}}}function n(){if(n.called){return}n.called=true;Array.prototype.map.call(document.getElementsByTagName("pre"),b).filter(Boolean).forEach(function(o){m(o,hljs.tabReplace)})}function k(){window.addEventListener("DOMContentLoaded",n,false);window.addEventListener("load",n,false)}var e={};this.LANGUAGES=e;this.highlight=d;this.highlightAuto=g;this.fixMarkup=i;this.highlightBlock=m;this.initHighlighting=n;this.initHighlightingOnLoad=k;this.IR="[a-zA-Z][a-zA-Z0-9_]*";this.UIR="[a-zA-Z_][a-zA-Z0-9_]*";this.NR="\\b\\d+(\\.\\d+)?";this.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";this.BNR="\\b(0b[01]+)";this.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|\\.|-|-=|/|/=|:|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";this.BE={b:"\\\\[\\s\\S]",r:0};this.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[this.BE],r:0};this.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[this.BE],r:0};this.CLCM={cN:"comment",b:"//",e:"$"};this.CBLCLM={cN:"comment",b:"/\\*",e:"\\*/"};this.HCM={cN:"comment",b:"#",e:"$"};this.NM={cN:"number",b:this.NR,r:0};this.CNM={cN:"number",b:this.CNR,r:0};this.BNM={cN:"number",b:this.BNR,r:0};this.inherit=function(q,r){var o={};for(var p in q){o[p]=q[p]}if(r){for(var p in r){o[p]=r[p]}}return o}}();hljs.LANGUAGES.cs=function(a){return{k:"abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual volatile void while ascending descending from get group into join let orderby partial select set value var where yield",c:[{cN:"comment",b:"///",e:"$",rB:true,c:[{cN:"xmlDocTag",b:"///|<!--|-->"},{cN:"xmlDocTag",b:"</?",e:">"}]},a.CLCM,a.CBLCLM,{cN:"preprocessor",b:"#",e:"$",k:"if else elif endif define undef warning error line region endregion pragma checksum"},{cN:"string",b:'@"',e:'"',c:[{b:'""'}]},a.ASM,a.QSM,a.CNM]}}(hljs);hljs.LANGUAGES.ruby=function(e){var a="[a-zA-Z_][a-zA-Z0-9_]*(\\!|\\?)?";var j="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?";var g={keyword:"and false then defined module in return redo if BEGIN retry end for true self when next until do begin unless END rescue nil else break undef not super class case require yield alias while ensure elsif or include"};var c={cN:"yardoctag",b:"@[A-Za-z]+"};var k=[{cN:"comment",b:"#",e:"$",c:[c]},{cN:"comment",b:"^\\=begin",e:"^\\=end",c:[c],r:10},{cN:"comment",b:"^__END__",e:"\\n$"}];var d={cN:"subst",b:"#\\{",e:"}",l:a,k:g};var i=[e.BE,d];var b=[{cN:"string",b:"'",e:"'",c:i,r:0},{cN:"string",b:'"',e:'"',c:i,r:0},{cN:"string",b:"%[qw]?\\(",e:"\\)",c:i},{cN:"string",b:"%[qw]?\\[",e:"\\]",c:i},{cN:"string",b:"%[qw]?{",e:"}",c:i},{cN:"string",b:"%[qw]?<",e:">",c:i,r:10},{cN:"string",b:"%[qw]?/",e:"/",c:i,r:10},{cN:"string",b:"%[qw]?%",e:"%",c:i,r:10},{cN:"string",b:"%[qw]?-",e:"-",c:i,r:10},{cN:"string",b:"%[qw]?\\|",e:"\\|",c:i,r:10}];var h={cN:"function",bWK:true,e:" |$|;",k:"def",c:[{cN:"title",b:j,l:a,k:g},{cN:"params",b:"\\(",e:"\\)",l:a,k:g}].concat(k)};var f=k.concat(b.concat([{cN:"class",bWK:true,e:"$|;",k:"class module",c:[{cN:"title",b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?",r:0},{cN:"inheritance",b:"<\\s*",c:[{cN:"parent",b:"("+e.IR+"::)?"+e.IR}]}].concat(k)},h,{cN:"constant",b:"(::)?(\\b[A-Z]\\w*(::)?)+",r:0},{cN:"symbol",b:":",c:b.concat([{b:j}]),r:0},{cN:"symbol",b:a+":",r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{cN:"number",b:"\\?\\w"},{cN:"variable",b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{b:"("+e.RSR+")\\s*",c:k.concat([{cN:"regexp",b:"/",e:"/[a-z]*",i:"\\n",c:[e.BE,d]}]),r:0}]));d.c=f;h.c[1].c=f;return{l:a,k:g,c:f}}(hljs);hljs.LANGUAGES.javascript=function(a){return{k:{keyword:"in if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const",literal:"true false null undefined NaN Infinity"},c:[a.ASM,a.QSM,a.CLCM,a.CBLCLM,a.CNM,{b:"("+a.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[a.CLCM,a.CBLCLM,{cN:"regexp",b:"/",e:"/[gim]*",i:"\\n",c:[{b:"\\\\/"}]},{b:"<",e:">;",sL:"xml"}],r:0},{cN:"function",bWK:true,e:"{",k:"function",c:[{cN:"title",b:"[A-Za-z$_][0-9A-Za-z$_]*"},{cN:"params",b:"\\(",e:"\\)",c:[a.CLCM,a.CBLCLM],i:"[\"'\\(]"}],i:"\\[|%"}]}}(hljs);hljs.LANGUAGES.xml=function(a){var c="[A-Za-z0-9\\._:-]+";var b={eW:true,c:[{cN:"attribute",b:c,r:0},{b:'="',rB:true,e:'"',c:[{cN:"value",b:'"',eW:true}]},{b:"='",rB:true,e:"'",c:[{cN:"value",b:"'",eW:true}]},{b:"=",c:[{cN:"value",b:"[^\\s/>]+"}]}]};return{cI:true,c:[{cN:"pi",b:"<\\?",e:"\\?>",r:10},{cN:"doctype",b:"<!DOCTYPE",e:">",r:10,c:[{b:"\\[",e:"\\]"}]},{cN:"comment",b:"<!--",e:"-->",r:10},{cN:"cdata",b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"tag",b:"<style(?=\\s|>|$)",e:">",k:{title:"style"},c:[b],starts:{e:"</style>",rE:true,sL:"css"}},{cN:"tag",b:"<script(?=\\s|>|$)",e:">",k:{title:"script"},c:[b],starts:{e:"<\/script>",rE:true,sL:"javascript"}},{b:"<%",e:"%>",sL:"vbscript"},{cN:"tag",b:"</?",e:"/?>",c:[{cN:"title",b:"[^ />]+"},b]}]}}(hljs);hljs.LANGUAGES.http=function(a){return{i:"\\S",c:[{cN:"status",b:"^HTTP/[0-9\\.]+",e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{cN:"request",b:"^[A-Z]+ (.*?) HTTP/[0-9\\.]+$",rB:true,e:"$",c:[{cN:"string",b:" ",e:" ",eB:true,eE:true}]},{cN:"attribute",b:"^\\w",e:": ",eE:true,i:"\\n|\\s|=",starts:{cN:"string",e:"$"}},{b:"\\n\\n",starts:{sL:"",eW:true}}]}}(hljs);hljs.LANGUAGES.java=function(a){return{k:"false synchronized int abstract float private char boolean static null if const for true while long throw strictfp finally protected import native final return void enum else break transient new catch instanceof byte super volatile case assert short package default double public try this switch continue throws",c:[{cN:"javadoc",b:"/\\*\\*",e:"\\*/",c:[{cN:"javadoctag",b:"@[A-Za-z]+"}],r:10},a.CLCM,a.CBLCLM,a.ASM,a.QSM,{cN:"class",bWK:true,e:"{",k:"class interface",i:":",c:[{bWK:true,k:"extends implements",r:10},{cN:"title",b:a.UIR}]},a.CNM,{cN:"annotation",b:"@[A-Za-z]+"}]}}(hljs);hljs.LANGUAGES.php=function(a){var e={cN:"variable",b:"\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*"};var b=[a.inherit(a.ASM,{i:null}),a.inherit(a.QSM,{i:null}),{cN:"string",b:'b"',e:'"',c:[a.BE]},{cN:"string",b:"b'",e:"'",c:[a.BE]}];var c=[a.BNM,a.CNM];var d={cN:"title",b:a.UIR};return{cI:true,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return implements parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception php_user_filter default die require __FUNCTION__ enddeclare final try this switch continue endfor endif declare unset true false namespace trait goto instanceof insteadof __DIR__ __NAMESPACE__ __halt_compiler",c:[a.CLCM,a.HCM,{cN:"comment",b:"/\\*",e:"\\*/",c:[{cN:"phpdoc",b:"\\s@[A-Za-z]+"}]},{cN:"comment",eB:true,b:"__halt_compiler.+?;",eW:true},{cN:"string",b:"<<<['\"]?\\w+['\"]?$",e:"^\\w+;",c:[a.BE]},{cN:"preprocessor",b:"<\\?php",r:10},{cN:"preprocessor",b:"\\?>"},e,{cN:"function",bWK:true,e:"{",k:"function",i:"\\$|\\[|%",c:[d,{cN:"params",b:"\\(",e:"\\)",c:["self",e,a.CBLCLM].concat(b).concat(c)}]},{cN:"class",bWK:true,e:"{",k:"class",i:"[:\\(\\$]",c:[{bWK:true,eW:true,k:"extends",c:[d]},d]},{b:"=>"}].concat(b).concat(c)}}(hljs);hljs.LANGUAGES.python=function(a){var f={cN:"prompt",b:"^(>>>|\\.\\.\\.) "};var c=[{cN:"string",b:"(u|b)?r?'''",e:"'''",c:[f],r:10},{cN:"string",b:'(u|b)?r?"""',e:'"""',c:[f],r:10},{cN:"string",b:"(u|r|ur)'",e:"'",c:[a.BE],r:10},{cN:"string",b:'(u|r|ur)"',e:'"',c:[a.BE],r:10},{cN:"string",b:"(b|br)'",e:"'",c:[a.BE]},{cN:"string",b:'(b|br)"',e:'"',c:[a.BE]}].concat([a.ASM,a.QSM]);var e={cN:"title",b:a.UIR};var d={cN:"params",b:"\\(",e:"\\)",c:["self",a.CNM,f].concat(c)};var b={bWK:true,e:":",i:"[${=;\\n]",c:[e,d],r:10};return{k:{keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda nonlocal|10",built_in:"None True False Ellipsis NotImplemented"},i:"(</|->|\\?)",c:c.concat([f,a.HCM,a.inherit(b,{cN:"function",k:"def"}),a.inherit(b,{cN:"class",k:"class"}),a.CNM,{cN:"decorator",b:"@",e:"$"},{b:"\\b(print|exec)\\("}])}}(hljs);hljs.LANGUAGES.perl=function(e){var a="getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qqfileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmgetsub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedirioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when";var d={cN:"subst",b:"[$@]\\{",e:"\\}",k:a,r:10};var b={cN:"variable",b:"\\$\\d"};var i={cN:"variable",b:"[\\$\\%\\@\\*](\\^\\w\\b|#\\w+(\\:\\:\\w+)*|[^\\s\\w{]|{\\w+}|\\w+(\\:\\:\\w*)*)"};var f=[e.BE,d,b,i];var h={b:"->",c:[{b:e.IR},{b:"{",e:"}"}]};var g={cN:"comment",b:"^(__END__|__DATA__)",e:"\\n$",r:5};var c=[b,i,e.HCM,g,{cN:"comment",b:"^\\=\\w",e:"\\=cut",eW:true},h,{cN:"string",b:"q[qwxr]?\\s*\\(",e:"\\)",c:f,r:5},{cN:"string",b:"q[qwxr]?\\s*\\[",e:"\\]",c:f,r:5},{cN:"string",b:"q[qwxr]?\\s*\\{",e:"\\}",c:f,r:5},{cN:"string",b:"q[qwxr]?\\s*\\|",e:"\\|",c:f,r:5},{cN:"string",b:"q[qwxr]?\\s*\\<",e:"\\>",c:f,r:5},{cN:"string",b:"qw\\s+q",e:"q",c:f,r:5},{cN:"string",b:"'",e:"'",c:[e.BE],r:0},{cN:"string",b:'"',e:'"',c:f,r:0},{cN:"string",b:"`",e:"`",c:[e.BE]},{cN:"string",b:"{\\w+}",r:0},{cN:"string",b:"-?\\w+\\s*\\=\\>",r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"("+e.RSR+"|\\b(split|return|print|reverse|grep)\\b)\\s*",k:"split return print reverse grep",r:0,c:[e.HCM,g,{cN:"regexp",b:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",r:10},{cN:"regexp",b:"(m|qr)?/",e:"/[a-z]*",c:[e.BE],r:0}]},{cN:"sub",bWK:true,e:"(\\s*\\(.*?\\))?[;{]",k:"sub",r:5},{cN:"operator",b:"-\\w\\b",r:0}];d.c=c;h.c[1].c=c;return{k:a,c:c}}(hljs);hljs.LANGUAGES.json=function(a){var e={literal:"true false null"};var d=[a.QSM,a.CNM];var c={cN:"value",e:",",eW:true,eE:true,c:d,k:e};var b={b:"{",e:"}",c:[{cN:"attribute",b:'\\s*"',e:'"\\s*:\\s*',eB:true,eE:true,c:[a.BE],i:"\\n",starts:c}],i:"\\S"};var f={b:"\\[",e:"\\]",c:[a.inherit(c,{cN:null})],i:"\\S"};d.splice(d.length,0,b,f);return{c:d,k:e,i:"\\S"}}(hljs);hljs.LANGUAGES.cpp=function(a){var b={keyword:"false int float while private char catch export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const struct for static_cast|10 union namespace unsigned long throw volatile static protected bool template mutable if public friend do return goto auto void enum else break new extern using true class asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue wchar_t inline delete alignof char16_t char32_t constexpr decltype noexcept nullptr static_assert thread_local restrict _Bool complex",built_in:"std string cin cout cerr clog stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr"};return{k:b,i:"</",c:[a.CLCM,a.CBLCLM,a.QSM,{cN:"string",b:"'\\\\?.",e:"'",i:"."},{cN:"number",b:"\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)"},a.CNM,{cN:"preprocessor",b:"#",e:"$"},{cN:"stl_container",b:"\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",e:">",k:b,r:10,c:["self"]}]}}(hljs);hljs.LANGUAGES.go=function(a){var b={keyword:"break default func interface select case map struct chan else goto package switch const fallthrough if range type continue for import return var go defer",constant:"true false iota nil",typename:"bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 uint16 uint32 uint64 int uint uintptr rune",built_in:"append cap close complex copy imag len make new panic print println real recover delete"};return{k:b,i:"</",c:[a.CLCM,a.CBLCLM,a.QSM,{cN:"string",b:"'",e:"[^\\\\]'",r:0},{cN:"string",b:"`",e:"`"},{cN:"number",b:"[^a-zA-Z_0-9](\\-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s)(\\+|\\-)?\\d+)?",r:0},a.CNM]}}(hljs);
parent/center.manager/src/main/webapp/WEB-INF/static/js/plugins/qiniu/http-performance.js View file @ a2758e4
  1 +/**
  2 + * @license httpPerformance v1.0.0
  3 + * License: MIT
  4 + * author: luoyeshu0507
  5 + *
  6 + * @description
  7 + *
  8 + * This object provides a utility for detailing the http request performance
  9 + *
  10 + */
  11 +;(function(window, undefined){
  12 + 'use strict';
  13 + var p = window.performance;
  14 + var httpPerformance = {
  15 + clear: function() {
  16 + p.clearMarks();
  17 + p.clearMeasures();
  18 + p.clearResourceTimings();
  19 + },
  20 + getAll: function() {
  21 + var performanceArr = [];
  22 + p.getEntries().forEach(function(item) {
  23 + performanceArr.push(httpPerformance.formatPerformance(item));
  24 + });
  25 + return performanceArr;
  26 + },
  27 + getByName: function(name) {
  28 + var performanceArr = [];
  29 + p.getEntriesByName(name).forEach(function(item) {
  30 + performanceArr.push(httpPerformance.formatPerformance(item));
  31 + });
  32 + return performanceArr;
  33 + },
  34 + formatPerformance: function(prt) { // PerformanceResourceTiming
  35 + return {
  36 + redirect: prt.redirectEnd - prt.redirectStart,
  37 + domainLookup: prt.domainLookupEnd - prt.domainLookupStart,
  38 + connect: prt.connectEnd - prt.connectStart,
  39 + request: prt.responseStart - prt.requestStart,
  40 + response: prt.responseEnd - prt.responseStart,
  41 +
  42 + entryType: prt.entryType,
  43 + initiatorType: prt.initiatorType,
  44 + name: prt.name,
  45 + duration: prt.duration,
  46 + };
  47 + }
  48 + };
  49 +
  50 + // support AMD and CMD
  51 + if (typeof module !== 'undefined' && module.exports) {
  52 + module.exports = httpPerformance;
  53 + } else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
  54 + define('httpPerformance', [], function () {
  55 + return httpPerformance;
  56 + });
  57 + } else {
  58 + window.httpPerformance = httpPerformance;
  59 + }
  60 +})(window);
parent/center.manager/src/main/webapp/WEB-INF/static/js/plugins/qiniu/main.js View file @ a2758e4
  1 +/*global Qiniu */
  2 +/*global plupload */
  3 +/*global FileProgress */
  4 +/*global hljs */
  5 +
  6 +
  7 +$(function() {
  8 + var uploader = Qiniu.uploader({
  9 + runtimes: 'html5,flash,html4',
  10 + browse_button: 'pickfiles',
  11 + container: 'container',
  12 + domain: 'http://img1.healthbaby.com.cn/',
  13 + drop_element: 'container',
  14 + max_file_size: '1000mb',
  15 + flash_swf_url: 'bower_components/plupload/js/Moxie.swf',
  16 + dragdrop: true,
  17 + chunk_size: '4mb',
  18 + multi_selection: !(mOxie.Env.OS.toLowerCase()==="ios"),
  19 + uptoken_url: $('#uptoken_url').val(),
  20 + // uptoken_func: function(){
  21 + // var ajax = new XMLHttpRequest();
  22 + // ajax.open('GET', $('#uptoken_url').val(), false);
  23 + // ajax.setRequestHeader("If-Modified-Since", "0");
  24 + // ajax.send();
  25 + // if (ajax.status === 200) {
  26 + // var res = JSON.parse(ajax.responseText);
  27 + // console.log('custom uptoken_func:' + res.uptoken);
  28 + // return res.uptoken;
  29 + // } else {
  30 + // console.log('custom uptoken_func err');
  31 + // return '';
  32 + // }
  33 + // },
  34 + get_new_uptoken: false,
  35 + // downtoken_url: '/downtoken',
  36 + // unique_names: true,
  37 + // save_key: true,
  38 + // x_vars: {
  39 + // 'id': '1234',
  40 + // 'time': function(up, file) {
  41 + // var time = (new Date()).getTime();
  42 + // // do something with 'time'
  43 + // return time;
  44 + // },
  45 + // },
  46 + auto_start: true,
  47 + log_level: 5,
  48 + init: {
  49 + 'FilesAdded': function(up, files) {
  50 + $('table').show();
  51 + $('#success').hide();
  52 + plupload.each(files, function(file) {
  53 + var progress = new FileProgress(file, 'fsUploadProgress');
  54 + progress.setStatus("等待...");
  55 + progress.bindUploadCancel(up);
  56 + });
  57 + },
  58 + 'BeforeUpload': function(up, file) {
  59 + var progress = new FileProgress(file, 'fsUploadProgress');
  60 + var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  61 + if (up.runtime === 'html5' && chunk_size) {
  62 + progress.setChunkProgess(chunk_size);
  63 + }
  64 + },
  65 + 'UploadProgress': function(up, file) {
  66 + var progress = new FileProgress(file, 'fsUploadProgress');
  67 + var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  68 + progress.setProgress(file.percent + "%", file.speed, chunk_size);
  69 + },
  70 + 'UploadComplete': function() {
  71 + $('#success').show();
  72 + },
  73 + 'FileUploaded': function(up, file, info) {
  74 + var progress = new FileProgress(file, 'fsUploadProgress');
  75 + progress.setComplete(up, info);
  76 + },
  77 + 'Error': function(up, err, errTip) {
  78 + $('table').show();
  79 + var progress = new FileProgress(err.file, 'fsUploadProgress');
  80 + progress.setError();
  81 + progress.setStatus(errTip);
  82 + }
  83 + // ,
  84 + // 'Key': function(up, file) {
  85 + // var key = "";
  86 + // // do something with key
  87 + // return key
  88 + // }
  89 + }
  90 + });
  91 +
  92 + uploader.bind('FileUploaded', function() {
  93 + console.log('hello man,a file is uploaded');
  94 + });
  95 + $('#container').on(
  96 + 'dragenter',
  97 + function(e) {
  98 + e.preventDefault();
  99 + $('#container').addClass('draging');
  100 + e.stopPropagation();
  101 + }
  102 + ).on('drop', function(e) {
  103 + e.preventDefault();
  104 + $('#container').removeClass('draging');
  105 + e.stopPropagation();
  106 + }).on('dragleave', function(e) {
  107 + e.preventDefault();
  108 + $('#container').removeClass('draging');
  109 + e.stopPropagation();
  110 + }).on('dragover', function(e) {
  111 + e.preventDefault();
  112 + $('#container').addClass('draging');
  113 + e.stopPropagation();
  114 + });
  115 +
  116 +
  117 +
  118 + $('#show_code').on('click', function() {
  119 + $('#myModal-code').modal();
  120 + $('pre code').each(function(i, e) {
  121 + hljs.highlightBlock(e);
  122 + });
  123 + });
  124 +
  125 +
  126 + $('body').on('click', 'table button.btn', function() {
  127 + $(this).parents('tr').next().toggle();
  128 + });
  129 +
  130 +
  131 + var getRotate = function(url) {
  132 + if (!url) {
  133 + return 0;
  134 + }
  135 + var arr = url.split('/');
  136 + for (var i = 0, len = arr.length; i < len; i++) {
  137 + if (arr[i] === 'rotate') {
  138 + return parseInt(arr[i + 1], 10);
  139 + }
  140 + }
  141 + return 0;
  142 + };
  143 +
  144 + $('#myModal-img .modal-body-footer').find('a').on('click', function() {
  145 + var img = $('#myModal-img').find('.modal-body img');
  146 + var key = img.data('key');
  147 + var oldUrl = img.attr('src');
  148 + var originHeight = parseInt(img.data('h'), 10);
  149 + var fopArr = [];
  150 + var rotate = getRotate(oldUrl);
  151 + if (!$(this).hasClass('no-disable-click')) {
  152 + $(this).addClass('disabled').siblings().removeClass('disabled');
  153 + if ($(this).data('imagemogr') !== 'no-rotate') {
  154 + fopArr.push({
  155 + 'fop': 'imageMogr2',
  156 + 'auto-orient': true,
  157 + 'strip': true,
  158 + 'rotate': rotate,
  159 + 'format': 'png'
  160 + });
  161 + }
  162 + } else {
  163 + $(this).siblings().removeClass('disabled');
  164 + var imageMogr = $(this).data('imagemogr');
  165 + if (imageMogr === 'left') {
  166 + rotate = rotate - 90 < 0 ? rotate + 270 : rotate - 90;
  167 + } else if (imageMogr === 'right') {
  168 + rotate = rotate + 90 > 360 ? rotate - 270 : rotate + 90;
  169 + }
  170 + fopArr.push({
  171 + 'fop': 'imageMogr2',
  172 + 'auto-orient': true,
  173 + 'strip': true,
  174 + 'rotate': rotate,
  175 + 'format': 'png'
  176 + });
  177 + }
  178 +
  179 + $('#myModal-img .modal-body-footer').find('a.disabled').each(function() {
  180 +
  181 + var watermark = $(this).data('watermark');
  182 + var imageView = $(this).data('imageview');
  183 + var imageMogr = $(this).data('imagemogr');
  184 +
  185 + if (watermark) {
  186 + fopArr.push({
  187 + fop: 'watermark',
  188 + mode: 1,
  189 + image: 'http://www.b1.qiniudn.com/images/logo-2.png',
  190 + dissolve: 100,
  191 + gravity: watermark,
  192 + dx: 100,
  193 + dy: 100
  194 + });
  195 + }
  196 +
  197 + if (imageView) {
  198 + var height;
  199 + switch (imageView) {
  200 + case 'large':
  201 + height = originHeight;
  202 + break;
  203 + case 'middle':
  204 + height = originHeight * 0.5;
  205 + break;
  206 + case 'small':
  207 + height = originHeight * 0.1;
  208 + break;
  209 + default:
  210 + height = originHeight;
  211 + break;
  212 + }
  213 + fopArr.push({
  214 + fop: 'imageView2',
  215 + mode: 3,
  216 + h: parseInt(height, 10),
  217 + q: 100,
  218 + format: 'png'
  219 + });
  220 + }
  221 +
  222 + if (imageMogr === 'no-rotate') {
  223 + fopArr.push({
  224 + 'fop': 'imageMogr2',
  225 + 'auto-orient': true,
  226 + 'strip': true,
  227 + 'rotate': 0,
  228 + 'format': 'png'
  229 + });
  230 + }
  231 + });
  232 +
  233 + var newUrl = Qiniu.pipeline(fopArr, key);
  234 +
  235 + var newImg = new Image();
  236 + img.attr('src', 'images/loading.gif');
  237 + newImg.onload = function() {
  238 + img.attr('src', newUrl);
  239 + img.parent('a').attr('href', newUrl);
  240 + };
  241 + newImg.src = newUrl;
  242 + return false;
  243 + });
  244 +
  245 +});
parent/center.manager/src/main/webapp/WEB-INF/static/js/plugins/qiniu/multiple.js View file @ a2758e4
  1 +/*global Qiniu */
  2 +/*global plupload */
  3 +/*global FileProgress */
  4 +/*global hljs */
  5 +
  6 +
  7 +$(function() {
  8 + var uploader = Qiniu.uploader({
  9 + runtimes: 'html5,flash,html4',
  10 + browse_button: 'pickfiles',
  11 + container: 'container',
  12 + drop_element: 'container',
  13 + max_file_size: '100mb',
  14 + flash_swf_url: 'js/plupload/Moxie.swf',
  15 + dragdrop: true,
  16 + chunk_size: '4mb',
  17 + uptoken_url: $('#uptoken_url').val(),
  18 + domain: $('#domain').val(),
  19 + auto_start: true,
  20 + init: {
  21 + 'FilesAdded': function(up, files) {
  22 + $('table').show();
  23 + $('#success').hide();
  24 + plupload.each(files, function(file) {
  25 + var progress = new FileProgress(file, 'fsUploadProgress');
  26 + progress.setStatus("等待...");
  27 + });
  28 + },
  29 + 'BeforeUpload': function(up, file) {
  30 + var progress = new FileProgress(file, 'fsUploadProgress');
  31 + var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  32 + if (up.runtime === 'html5' && chunk_size) {
  33 + progress.setChunkProgess(chunk_size);
  34 + }
  35 + },
  36 + 'UploadProgress': function(up, file) {
  37 + var progress = new FileProgress(file, 'fsUploadProgress');
  38 + var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  39 +
  40 + progress.setProgress(file.percent + "%", file.speed, chunk_size);
  41 + },
  42 + 'UploadComplete': function() {
  43 + $('#success').show();
  44 + },
  45 + 'FileUploaded': function(up, file, info) {
  46 + var progress = new FileProgress(file, 'fsUploadProgress');
  47 + progress.setComplete(up, info);
  48 + },
  49 + 'Error': function(up, err, errTip) {
  50 + $('table').show();
  51 + var progress = new FileProgress(err.file, 'fsUploadProgress');
  52 + progress.setError();
  53 + progress.setStatus(errTip);
  54 + }
  55 + }
  56 + });
  57 +
  58 + uploader.bind('FileUploaded', function() {
  59 + console.log('hello man,a file is uploaded');
  60 + });
  61 +
  62 + var Q2 = new QiniuJsSDK();
  63 + var uploader2 = Q2.uploader({
  64 + runtimes: 'html5,flash,html4',
  65 + browse_button: 'pickfiles2',
  66 + container: 'container2',
  67 + drop_element: 'container2',
  68 + max_file_size: '100mb',
  69 + flash_swf_url: 'js/plupload/Moxie.swf',
  70 + dragdrop: true,
  71 + chunk_size: '4mb',
  72 + uptoken_url: $('#uptoken_url').val(),
  73 + domain: $('#domain').val(),
  74 + auto_start: true,
  75 + init: {
  76 + 'FilesAdded': function(up, files) {
  77 + $('table').show();
  78 + $('#success').hide();
  79 + plupload.each(files, function(file) {
  80 + var progress = new FileProgress(file, 'fsUploadProgress');
  81 + progress.setStatus("等待...");
  82 + });
  83 + },
  84 + 'BeforeUpload': function(up, file) {
  85 + var progress = new FileProgress(file, 'fsUploadProgress');
  86 + var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  87 + if (up.runtime === 'html5' && chunk_size) {
  88 + progress.setChunkProgess(chunk_size);
  89 + }
  90 + },
  91 + 'UploadProgress': function(up, file) {
  92 + var progress = new FileProgress(file, 'fsUploadProgress');
  93 + var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  94 +
  95 + progress.setProgress(file.percent + "%", file.speed, chunk_size);
  96 + },
  97 + 'UploadComplete': function() {
  98 + $('#success').show();
  99 + },
  100 + 'FileUploaded': function(up, file, info) {
  101 + var progress = new FileProgress(file, 'fsUploadProgress');
  102 + progress.setComplete(up, info);
  103 + },
  104 + 'Error': function(up, err, errTip) {
  105 + $('table').show();
  106 + var progress = new FileProgress(err.file, 'fsUploadProgress');
  107 + progress.setError();
  108 + progress.setStatus(errTip);
  109 + }
  110 + }
  111 + });
  112 +
  113 + uploader2.bind('FileUploaded', function() {
  114 + console.log('hello man 2,a file is uploaded');
  115 + });
  116 +
  117 + $('#container').on(
  118 + 'dragenter',
  119 + function(e) {
  120 + e.preventDefault();
  121 + $('#container').addClass('draging');
  122 + e.stopPropagation();
  123 + }
  124 + ).on('drop', function(e) {
  125 + e.preventDefault();
  126 + $('#container').removeClass('draging');
  127 + e.stopPropagation();
  128 + }).on('dragleave', function(e) {
  129 + e.preventDefault();
  130 + $('#container').removeClass('draging');
  131 + e.stopPropagation();
  132 + }).on('dragover', function(e) {
  133 + e.preventDefault();
  134 + $('#container').addClass('draging');
  135 + e.stopPropagation();
  136 + });
  137 +
  138 +
  139 +
  140 + $('#show_code').on('click', function() {
  141 + $('#myModal-code').modal();
  142 + $('pre code').each(function(i, e) {
  143 + hljs.highlightBlock(e);
  144 + });
  145 + });
  146 +
  147 +
  148 + $('body').on('click', 'table button.btn', function() {
  149 + $(this).parents('tr').next().toggle();
  150 + });
  151 +
  152 +
  153 + var getRotate = function(url) {
  154 + if (!url) {
  155 + return 0;
  156 + }
  157 + var arr = url.split('/');
  158 + for (var i = 0, len = arr.length; i < len; i++) {
  159 + if (arr[i] === 'rotate') {
  160 + return parseInt(arr[i + 1], 10);
  161 + }
  162 + }
  163 + return 0;
  164 + };
  165 +
  166 + $('#myModal-img .modal-body-footer').find('a').on('click', function() {
  167 + var img = $('#myModal-img').find('.modal-body img');
  168 + var key = img.data('key');
  169 + var oldUrl = img.attr('src');
  170 + var originHeight = parseInt(img.data('h'), 10);
  171 + var fopArr = [];
  172 + var rotate = getRotate(oldUrl);
  173 + if (!$(this).hasClass('no-disable-click')) {
  174 + $(this).addClass('disabled').siblings().removeClass('disabled');
  175 + if ($(this).data('imagemogr') !== 'no-rotate') {
  176 + fopArr.push({
  177 + 'fop': 'imageMogr2',
  178 + 'auto-orient': true,
  179 + 'strip': true,
  180 + 'rotate': rotate,
  181 + 'format': 'png'
  182 + });
  183 + }
  184 + } else {
  185 + $(this).siblings().removeClass('disabled');
  186 + var imageMogr = $(this).data('imagemogr');
  187 + if (imageMogr === 'left') {
  188 + rotate = rotate - 90 < 0 ? rotate + 270 : rotate - 90;
  189 + } else if (imageMogr === 'right') {
  190 + rotate = rotate + 90 > 360 ? rotate - 270 : rotate + 90;
  191 + }
  192 + fopArr.push({
  193 + 'fop': 'imageMogr2',
  194 + 'auto-orient': true,
  195 + 'strip': true,
  196 + 'rotate': rotate,
  197 + 'format': 'png'
  198 + });
  199 + }
  200 +
  201 + $('#myModal-img .modal-body-footer').find('a.disabled').each(function() {
  202 +
  203 + var watermark = $(this).data('watermark');
  204 + var imageView = $(this).data('imageview');
  205 + var imageMogr = $(this).data('imagemogr');
  206 +
  207 + if (watermark) {
  208 + fopArr.push({
  209 + fop: 'watermark',
  210 + mode: 1,
  211 + image: 'http://www.b1.qiniudn.com/images/logo-2.png',
  212 + dissolve: 100,
  213 + gravity: watermark,
  214 + dx: 100,
  215 + dy: 100
  216 + });
  217 + }
  218 +
  219 + if (imageView) {
  220 + var height;
  221 + switch (imageView) {
  222 + case 'large':
  223 + height = originHeight;
  224 + break;
  225 + case 'middle':
  226 + height = originHeight * 0.5;
  227 + break;
  228 + case 'small':
  229 + height = originHeight * 0.1;
  230 + break;
  231 + default:
  232 + height = originHeight;
  233 + break;
  234 + }
  235 + fopArr.push({
  236 + fop: 'imageView2',
  237 + mode: 3,
  238 + h: parseInt(height, 10),
  239 + q: 100,
  240 + format: 'png'
  241 + });
  242 + }
  243 +
  244 + if (imageMogr === 'no-rotate') {
  245 + fopArr.push({
  246 + 'fop': 'imageMogr2',
  247 + 'auto-orient': true,
  248 + 'strip': true,
  249 + 'rotate': 0,
  250 + 'format': 'png'
  251 + });
  252 + }
  253 + });
  254 +
  255 + var newUrl = Qiniu.pipeline(fopArr, key);
  256 +
  257 + var newImg = new Image();
  258 + img.attr('src', 'images/loading.gif');
  259 + newImg.onload = function() {
  260 + img.attr('src', newUrl);
  261 + img.parent('a').attr('href', newUrl);
  262 + };
  263 + newImg.src = newUrl;
  264 + return false;
  265 + });
  266 +
  267 +});
parent/center.manager/src/main/webapp/WEB-INF/static/js/plugins/qiniu/performance.js View file @ a2758e4
  1 +Vue.component('zone-list', {
  2 + props: ['hostMap', 'currentZone', 'switchZone', 'selectedHost'],
  3 + template: '<div class="uphosts-list"><ul><li v-for="item in hostMap" :class="{on: item.zone == currentZone}" @click="switchZone(item.zone)">{{item.zoneZh}}</li></ul><ul><li v-for="item in hostMap" :class="{on: item.zone == currentZone}"><label v-for="uphost in item.uphosts"><input type="radio" v-model="selectedHost.host" :value="uphost"/>{{uphost}}</label></li></ul></div>'
  4 +});
  5 +Vue.component('upload-performance', {
  6 + props: ['per'],
  7 + template: '<div class="up-performance"><div class="per-title">上传耗时:</div>' +
  8 + '<table>' +
  9 + '<tr><th>类型</th><th>耗时 / ms</th></tr>' +
  10 + '<tr><td>重定向:</td><td>{{per.redirect | tofixed(2)}}</td></tr>' +
  11 + '<tr><td>DNS 查询:</td><td>{{per.domainLookup | tofixed(2)}}</td></tr>' +
  12 + '<tr><td>建立连接:</td><td>{{per.connect | tofixed(2)}}</td></tr>' +
  13 + '<tr><td>发送数据到开始响应:</td><td>{{per.request | tofixed(2)}}</td></tr>' +
  14 + '<tr><td>接收响应:</td><td>{{per.response | tofixed(2)}}</td></tr>' +
  15 + '<tr><td>总耗时:</td><td>{{per.duration | tofixed(2)}}</td></tr></table>' +
  16 + '</div>'
  17 +});
  18 +Vue.component('up-headers', {
  19 + props: ['headers'],
  20 + template: '<div class="up-headers"><div class="per-title">响应头:</div><table><tr><th>类型</th><th>值</th></tr><tr v-for="header in headers"><td>{{header.key}}</td><td>{{header.val}}</td></tr></table></div>'
  21 +});
  22 +Vue.filter('tofixed', function (val, size) {
  23 + return val.toFixed(size);
  24 +});
  25 +
  26 +var app = new Vue({
  27 + el: '#app',
  28 + data: {
  29 + currentZone: 'z0',
  30 + selectedHost: {
  31 + host: ''
  32 + },
  33 + currentToken: '',
  34 + loadMessage: '',
  35 + hostMap: [
  36 + {
  37 + zone: 'z0',
  38 + zoneZh: '华东',
  39 + token: 'xozWSPMxkMjIVoHg2JyXq4-7-oJaEADLOKHVR0vU:hzD116IsDOpb4gjzyPg7ngg4Qjs=:eyJzY29wZSI6Impzc2RrOmEuanBnIiwiZGVhZGxpbmUiOjIxMTQzODA4MDAwMDAsImZzaXplTGltaXQiOjEwMDAwMDB9',
  40 + uphosts: [
  41 + 'http://up.qiniu.com',
  42 + 'http://upload.qiniu.com',
  43 + 'https://up.qbox.me',
  44 + 'https://upload.qbox.me'
  45 + ]
  46 + },
  47 + {
  48 + zone: 'z1',
  49 + zoneZh: '华北',
  50 + token: 'xozWSPMxkMjIVoHg2JyXq4-7-oJaEADLOKHVR0vU:9RFuA13c6pp-O2aIOe1UfTI3rlo=:eyJzY29wZSI6Impzc2RrLXoxOmEuanBnIiwiZGVhZGxpbmUiOjIxMTQzODA4MDAwMDAsImZzaXplTGltaXQiOjEwMDAwMDB9',
  51 + uphosts: [
  52 + 'http://up-z1.qiniu.com',
  53 + 'http://upload-z1.qiniu.com',
  54 + 'https://up-z1.qbox.me',
  55 + 'https://upload-z1.qbox.me'
  56 + ]
  57 + },
  58 + {
  59 + zone: 'z2',
  60 + zoneZh: '华南',
  61 + token: 'xozWSPMxkMjIVoHg2JyXq4-7-oJaEADLOKHVR0vU:qmDBxiYviu0tg2hZzCFHjCZM3-w=:eyJzY29wZSI6Impzc2RrLXoyOmEuanBnIiwiZGVhZGxpbmUiOjIxMTQzODA4MDAwMDAsImZzaXplTGltaXQiOjEwMDAwMDB9',
  62 + uphosts: [
  63 + 'http://up-z2.qiniu.com',
  64 + 'http://upload-z2.qiniu.com',
  65 + 'https://up-z2.qbox.me',
  66 + 'https://upload-z2.qbox.me'
  67 + ]
  68 + },
  69 + {
  70 + zone: 'na0',
  71 + zoneZh: '北美',
  72 + token: 'xozWSPMxkMjIVoHg2JyXq4-7-oJaEADLOKHVR0vU:DMPzTGGhX3HY0ph99YfAK_y-0XM=:eyJzY29wZSI6Impzc2RrLW5hMDphLmpwZyIsImRlYWRsaW5lIjoyMTE0MzgwODAwMDAwLCJmc2l6ZUxpbWl0IjoxMDAwMDAwfQ==',
  73 + uphosts: [
  74 + 'http://up-na0.qiniu.com',
  75 + 'http://upload-na0.qiniu.com',
  76 + 'https://up-na0.qbox.me',
  77 + 'https://upload-na0.qbox.me'
  78 + ]
  79 + },
  80 + ],
  81 + isPerformanceSupported: true,
  82 + performance: null,
  83 + headers: null
  84 + },
  85 + methods: {
  86 + renderHtml: function() {},
  87 + post: function(opt) {
  88 + var xmlHttp = new XMLHttpRequest();
  89 + xmlHttp.open('POST', opt.url, true);
  90 + xmlHttp.setRequestHeader('X-Qiniu-Performance', 'true');
  91 + xmlHttp.onreadystatechange = function () {
  92 + if (xmlHttp.readyState == 4) {
  93 + if (xmlHttp.status == 200) {
  94 + opt.success(xmlHttp);
  95 + } else {
  96 + opt.error(xmlHttp.responseText);
  97 + }
  98 + }
  99 + };
  100 + xmlHttp.upload.onprogress = opt.progress;
  101 + xmlHttp.send(opt.data);
  102 + },
  103 + uploadTest: function() {
  104 + if(!this.selectedHost.host) return;
  105 + this.resetResult();
  106 + var self = this;
  107 + this.post({
  108 + url: this.selectedHost.host,
  109 + data: this.mockDate(),
  110 + progress: function(e) {
  111 + if (e.lengthComputable) {
  112 + var percent = e.loaded/e.total*100;
  113 + self.loadMessage = '模拟数据上传:' + e.loaded + " / " + e.total+" bytes 完成:" + percent.toFixed(2) + "%";
  114 + }
  115 + },
  116 + success: function(xhr) {
  117 + self.formateHeader(xhr.getAllResponseHeaders());
  118 + self.getPerformance();
  119 + },
  120 + error: function(res) {
  121 + self.loadMessage = '上传失败:' + res;
  122 + }
  123 + });
  124 + },
  125 + mockDate: function(size) {
  126 + var f = new FormData(document.getElementById("testform"));
  127 + f.append('file', this.dataURLtoBlob(this.randomBase64(size)));
  128 + f.append('token', this.currentToken);
  129 + return f;
  130 + },
  131 + randomBase64: function() {
  132 + var dataurl = 'data:image/jpeg;base64,';
  133 + var len = parseInt(Math.random()*(1330000-1100000+1)+1100000, 10);
  134 + while (dataurl.length < len) {
  135 + dataurl += Math.random > 0.5 ? '/9j/4AAQSkZJRgABAQAASABIAAD/4Q' : '/9j/4AAQSkZJRgABAQAASABIAAD/4W';
  136 + }
  137 + return dataurl;
  138 + },
  139 + dataURLtoBlob: function(dataurl) {
  140 + var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  141 + bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  142 + while(n--){
  143 + u8arr[n] = bstr.charCodeAt(n);
  144 + }
  145 + return new Blob([u8arr], {type:mime});
  146 + },
  147 + resetResult: function() {
  148 + for (var i = 0; i < this.hostMap.length; i++) {
  149 + if (this.hostMap[i].zone === this.currentZone) {
  150 + this.currentToken = this.hostMap[i].token;
  151 + break;
  152 + }
  153 + }
  154 + this.performance = null;
  155 + this.headers = null;
  156 + },
  157 + switchZone: function(zone) {
  158 + this.currentZone = zone;
  159 + this.selectedHost.host = '';
  160 + },
  161 + getPerformance: function() {
  162 + var per = httpPerformance.getByName(this.selectedHost.host + '/');
  163 + if(per.length == 2) {
  164 + per[1].redirect = per[0].redirect;
  165 + per[1].domainLookup = per[0].domainLookup;
  166 + per[1].connect = per[0].connect;
  167 + }
  168 + this.performance = per[1] || per[0]; // 跨域有时候会先发送一个 option 请求,并不是真的上传请求。
  169 + },
  170 + formateHeader: function(headers) {
  171 + var list = [];
  172 + headers.match(/.+/mg).map(function(item) {
  173 + var index = item.indexOf(':');
  174 + var o = {
  175 + key: item.substr(0, index),
  176 + val: item.substr(index + 1)
  177 + };
  178 + list.push(o);
  179 + });
  180 + this.headers = list;
  181 + }
  182 + },
  183 + created: function() {
  184 + this.isPerformanceSupported = !!(window.performance && window.performance.getEntries);
  185 + }
  186 +});
parent/center.manager/src/main/webapp/WEB-INF/static/js/plugins/qiniu/qiniu.js View file @ a2758e4
Diff suppressed. Click to show
  1 +/*!
  2 + * qiniu-js-sdk v@VERSION
  3 + *
  4 + * Copyright 2015 by Qiniu
  5 + * Released under GPL V2 License.
  6 + *
  7 + * GitHub: http://github.com/qiniu/js-sdk
  8 + *
  9 + * Date: @DATE
  10 +*/
  11 +
  12 +/*global plupload ,mOxie*/
  13 +/*global ActiveXObject */
  14 +/*exported Qiniu */
  15 +/*exported QiniuJsSDK */
  16 +
  17 +;(function( global ){
  18 +
  19 +/**
  20 + * Creates new cookie or removes cookie with negative expiration
  21 + * @param key The key or identifier for the store
  22 + * @param value Contents of the store
  23 + * @param exp Expiration - creation defaults to 30 days
  24 + */
  25 +function createCookie(key, value, exp) {
  26 + var date = new Date();
  27 + date.setTime(date.getTime() + (exp * 24 * 60 * 60 * 1000));
  28 + var expires = "; expires=" + date.toGMTString();
  29 + document.cookie = key + "=" + value + expires + "; path=/";
  30 +}
  31 +
  32 +/**
  33 + * Returns contents of cookie
  34 + * @param key The key or identifier for the store
  35 + */
  36 +function readCookie(key) {
  37 + var nameEQ = key + "=";
  38 + var ca = document.cookie.split(';');
  39 + for (var i = 0, max = ca.length; i < max; i++) {
  40 + var c = ca[i];
  41 + while (c.charAt(0) === ' ') {
  42 + c = c.substring(1, c.length);
  43 + }
  44 + if (c.indexOf(nameEQ) === 0) {
  45 + return c.substring(nameEQ.length, c.length);
  46 + }
  47 + }
  48 + return null;
  49 +}
  50 +
  51 +// if current browser is not support localStorage
  52 +// use cookie to make a polyfill
  53 +if ( !window.localStorage ) {
  54 + window.localStorage = {
  55 + setItem: function (key, value) {
  56 + createCookie(key, value, 30);
  57 + },
  58 + getItem: function (key) {
  59 + return readCookie(key);
  60 + },
  61 + removeItem: function (key) {
  62 + createCookie(key, '', -1);
  63 + }
  64 + };
  65 +}
  66 +
  67 +function QiniuJsSDK() {
  68 +
  69 + var that = this;
  70 +
  71 + /**
  72 + * detect IE version
  73 + * if current browser is not IE
  74 + * it will return false
  75 + * else
  76 + * it will return version of current IE browser
  77 + * @return {Number|Boolean} IE version or false
  78 + */
  79 + this.detectIEVersion = function() {
  80 + var v = 4,
  81 + div = document.createElement('div'),
  82 + all = div.getElementsByTagName('i');
  83 + while (
  84 + div.innerHTML = '<!--[if gt IE ' + v + ']><i></i><![endif]-->',
  85 + all[0]
  86 + ) {
  87 + v++;
  88 + }
  89 + return v > 4 ? v : false;
  90 + };
  91 +
  92 + var logger = {
  93 + MUTE: 0,
  94 + FATA: 1,
  95 + ERROR: 2,
  96 + WARN: 3,
  97 + INFO: 4,
  98 + DEBUG: 5,
  99 + TRACE: 6,
  100 + level: 0
  101 + };
  102 +
  103 + function log(type, args){
  104 + var header = "[qiniu-js-sdk]["+type+"]";
  105 + var msg = header;
  106 + for (var i = 0; i < args.length; i++) {
  107 + if (typeof args[i] === "string") {
  108 + msg += " " + args[i];
  109 + } else {
  110 + msg += " " + that.stringifyJSON(args[i]);
  111 + }
  112 + }
  113 + if (that.detectIEVersion()) {
  114 + // http://stackoverflow.com/questions/5538972/console-log-apply-not-working-in-ie9
  115 + //var log = Function.prototype.bind.call(console.log, console);
  116 + //log.apply(console, args);
  117 + console.log(msg);
  118 + }else{
  119 + args.unshift(header);
  120 + console.log.apply(console, args);
  121 + }
  122 + if (document.getElementById('qiniu-js-sdk-log')) {
  123 + document.getElementById('qiniu-js-sdk-log').innerHTML += '<p>'+msg+'</p>';
  124 + }
  125 + }
  126 +
  127 + function makeLogFunc(code){
  128 + var func = code.toLowerCase();
  129 + logger[func] = function(){
  130 + // logger[func].history = logger[func].history || [];
  131 + // logger[func].history.push(arguments);
  132 + if(window.console && window.console.log && logger.level>=logger[code]){
  133 + var args = Array.prototype.slice.call(arguments);
  134 + log(func,args);
  135 + }
  136 + };
  137 + }
  138 +
  139 + for (var property in logger){
  140 + if (logger.hasOwnProperty(property) && (typeof logger[property]) === "number" && !logger.hasOwnProperty(property.toLowerCase())) {
  141 + makeLogFunc(property);
  142 + }
  143 + }
  144 +
  145 +
  146 + var qiniuUploadUrl;
  147 + if (window.location.protocol === 'https:') {
  148 + qiniuUploadUrl = 'https://up.qbox.me';
  149 + } else {
  150 + qiniuUploadUrl = 'http://upload.qiniu.com';
  151 + }
  152 +
  153 + /**
  154 + * qiniu upload urls
  155 + * 'qiniuUploadUrls' is used to change target when current url is not avaliable
  156 + * @type {Array}
  157 + */
  158 + var qiniuUploadUrls = [
  159 + "http://upload.qiniu.com",
  160 + "http://up.qiniu.com"
  161 + ];
  162 +
  163 + var qiniuUpHosts = {
  164 + "http": [
  165 + "http://upload.qiniu.com",
  166 + "http://up.qiniu.com"
  167 + ],
  168 + "https": [
  169 + "https://up.qbox.me"
  170 + ]
  171 + };
  172 +
  173 + var changeUrlTimes = 0;
  174 +
  175 + /**
  176 + * reset upload url
  177 + * if current page protocal is https
  178 + * it will always return 'https://up.qbox.me'
  179 + * else
  180 + * it will set 'qiniuUploadUrl' value with 'qiniuUploadUrls' looply
  181 + */
  182 + this.resetUploadUrl = function(){
  183 + var hosts = window.location.protocol === 'https:' ? qiniuUpHosts.https : qiniuUpHosts.http;
  184 + var i = changeUrlTimes % hosts.length;
  185 + qiniuUploadUrl = hosts[i];
  186 + changeUrlTimes++;
  187 + logger.debug('resetUploadUrl: '+qiniuUploadUrl);
  188 + };
  189 +
  190 + // this.resetUploadUrl();
  191 +
  192 +
  193 + /**
  194 + * is image
  195 + * @param {String} url of a file
  196 + * @return {Boolean} file is a image or not
  197 + */
  198 + this.isImage = function(url) {
  199 + url = url.split(/[?#]/)[0];
  200 + return (/\.(png|jpg|jpeg|gif|bmp)$/i).test(url);
  201 + };
  202 +
  203 + /**
  204 + * get file extension
  205 + * @param {String} filename
  206 + * @return {String} file extension
  207 + * @example
  208 + * input: test.txt
  209 + * output: txt
  210 + */
  211 + this.getFileExtension = function(filename) {
  212 + var tempArr = filename.split(".");
  213 + var ext;
  214 + if (tempArr.length === 1 || (tempArr[0] === "" && tempArr.length === 2)) {
  215 + ext = "";
  216 + } else {
  217 + ext = tempArr.pop().toLowerCase(); //get the extension and make it lower-case
  218 + }
  219 + return ext;
  220 + };
  221 +
  222 + /**
  223 + * encode string by utf8
  224 + * @param {String} string to encode
  225 + * @return {String} encoded string
  226 + */
  227 + this.utf8_encode = function(argString) {
  228 + // http://kevin.vanzonneveld.net
  229 + // + original by: Webtoolkit.info (http://www.webtoolkit.info/)
  230 + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  231 + // + improved by: sowberry
  232 + // + tweaked by: Jack
  233 + // + bugfixed by: Onno Marsman
  234 + // + improved by: Yves Sucaet
  235 + // + bugfixed by: Onno Marsman
  236 + // + bugfixed by: Ulrich
  237 + // + bugfixed by: Rafal Kukawski
  238 + // + improved by: kirilloid
  239 + // + bugfixed by: kirilloid
  240 + // * example 1: this.utf8_encode('Kevin van Zonneveld');
  241 + // * returns 1: 'Kevin van Zonneveld'
  242 +
  243 + if (argString === null || typeof argString === 'undefined') {
  244 + return '';
  245 + }
  246 +
  247 + var string = (argString + ''); // .replace(/\r\n/g, '\n').replace(/\r/g, '\n');
  248 + var utftext = '',
  249 + start, end, stringl = 0;
  250 +
  251 + start = end = 0;
  252 + stringl = string.length;
  253 + for (var n = 0; n < stringl; n++) {
  254 + var c1 = string.charCodeAt(n);
  255 + var enc = null;
  256 +
  257 + if (c1 < 128) {
  258 + end++;
  259 + } else if (c1 > 127 && c1 < 2048) {
  260 + enc = String.fromCharCode(
  261 + (c1 >> 6) | 192, (c1 & 63) | 128
  262 + );
  263 + } else if (c1 & 0xF800 ^ 0xD800 > 0) {
  264 + enc = String.fromCharCode(
  265 + (c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
  266 + );
  267 + } else { // surrogate pairs
  268 + if (c1 & 0xFC00 ^ 0xD800 > 0) {
  269 + throw new RangeError('Unmatched trail surrogate at ' + n);
  270 + }
  271 + var c2 = string.charCodeAt(++n);
  272 + if (c2 & 0xFC00 ^ 0xDC00 > 0) {
  273 + throw new RangeError('Unmatched lead surrogate at ' + (n - 1));
  274 + }
  275 + c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
  276 + enc = String.fromCharCode(
  277 + (c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
  278 + );
  279 + }
  280 + if (enc !== null) {
  281 + if (end > start) {
  282 + utftext += string.slice(start, end);
  283 + }
  284 + utftext += enc;
  285 + start = end = n + 1;
  286 + }
  287 + }
  288 +
  289 + if (end > start) {
  290 + utftext += string.slice(start, stringl);
  291 + }
  292 +
  293 + return utftext;
  294 + };
  295 +
  296 + this.base64_decode = function (data) {
  297 + // http://kevin.vanzonneveld.net
  298 + // + original by: Tyler Akins (http://rumkin.com)
  299 + // + improved by: Thunder.m
  300 + // + input by: Aman Gupta
  301 + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  302 + // + bugfixed by: Onno Marsman
  303 + // + bugfixed by: Pellentesque Malesuada
  304 + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  305 + // + input by: Brett Zamir (http://brett-zamir.me)
  306 + // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  307 + // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  308 + // * returns 1: 'Kevin van Zonneveld'
  309 + // mozilla has this native
  310 + // - but breaks in 2.0.0.12!
  311 + //if (typeof this.window['atob'] == 'function') {
  312 + // return atob(data);
  313 + //}
  314 + var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  315 + var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
  316 + ac = 0,
  317 + dec = "",
  318 + tmp_arr = [];
  319 +
  320 + if (!data) {
  321 + return data;
  322 + }
  323 +
  324 + data += '';
  325 +
  326 + do { // unpack four hexets into three octets using index points in b64
  327 + h1 = b64.indexOf(data.charAt(i++));
  328 + h2 = b64.indexOf(data.charAt(i++));
  329 + h3 = b64.indexOf(data.charAt(i++));
  330 + h4 = b64.indexOf(data.charAt(i++));
  331 +
  332 + bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
  333 +
  334 + o1 = bits >> 16 & 0xff;
  335 + o2 = bits >> 8 & 0xff;
  336 + o3 = bits & 0xff;
  337 +
  338 + if (h3 === 64) {
  339 + tmp_arr[ac++] = String.fromCharCode(o1);
  340 + } else if (h4 === 64) {
  341 + tmp_arr[ac++] = String.fromCharCode(o1, o2);
  342 + } else {
  343 + tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  344 + }
  345 + } while (i < data.length);
  346 +
  347 + dec = tmp_arr.join('');
  348 +
  349 + return dec;
  350 + };
  351 +
  352 + /**
  353 + * encode data by base64
  354 + * @param {String} data to encode
  355 + * @return {String} encoded data
  356 + */
  357 + this.base64_encode = function(data) {
  358 + // http://kevin.vanzonneveld.net
  359 + // + original by: Tyler Akins (http://rumkin.com)
  360 + // + improved by: Bayron Guevara
  361 + // + improved by: Thunder.m
  362 + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  363 + // + bugfixed by: Pellentesque Malesuada
  364 + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  365 + // - depends on: this.utf8_encode
  366 + // * example 1: this.base64_encode('Kevin van Zonneveld');
  367 + // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  368 + // mozilla has this native
  369 + // - but breaks in 2.0.0.12!
  370 + //if (typeof this.window['atob'] == 'function') {
  371 + // return atob(data);
  372 + //}
  373 + var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  374 + var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
  375 + ac = 0,
  376 + enc = '',
  377 + tmp_arr = [];
  378 +
  379 + if (!data) {
  380 + return data;
  381 + }
  382 +
  383 + data = this.utf8_encode(data + '');
  384 +
  385 + do { // pack three octets into four hexets
  386 + o1 = data.charCodeAt(i++);
  387 + o2 = data.charCodeAt(i++);
  388 + o3 = data.charCodeAt(i++);
  389 +
  390 + bits = o1 << 16 | o2 << 8 | o3;
  391 +
  392 + h1 = bits >> 18 & 0x3f;
  393 + h2 = bits >> 12 & 0x3f;
  394 + h3 = bits >> 6 & 0x3f;
  395 + h4 = bits & 0x3f;
  396 +
  397 + // use hexets to index into b64, and append result to encoded string
  398 + tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  399 + } while (i < data.length);
  400 +
  401 + enc = tmp_arr.join('');
  402 +
  403 + switch (data.length % 3) {
  404 + case 1:
  405 + enc = enc.slice(0, -2) + '==';
  406 + break;
  407 + case 2:
  408 + enc = enc.slice(0, -1) + '=';
  409 + break;
  410 + }
  411 +
  412 + return enc;
  413 + };
  414 +
  415 + /**
  416 + * encode string in url by base64
  417 + * @param {String} string in url
  418 + * @return {String} encoded string
  419 + */
  420 + this.URLSafeBase64Encode = function(v) {
  421 + v = this.base64_encode(v);
  422 + return v.replace(/\//g, '_').replace(/\+/g, '-');
  423 + };
  424 +
  425 + this.URLSafeBase64Decode = function(v) {
  426 + v = v.replace(/_/g, '/').replace(/-/g, '+');
  427 + return this.base64_decode(v);
  428 + };
  429 +
  430 + // TODO: use mOxie
  431 + /**
  432 + * craete object used to AJAX
  433 + * @return {Object}
  434 + */
  435 + this.createAjax = function(argument) {
  436 + var xmlhttp = {};
  437 + if (window.XMLHttpRequest) {
  438 + xmlhttp = new XMLHttpRequest();
  439 + } else {
  440 + xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  441 + }
  442 + return xmlhttp;
  443 + };
  444 +
  445 + // TODO: enhance IE compatibility
  446 + /**
  447 + * parse json string to javascript object
  448 + * @param {String} json string
  449 + * @return {Object} object
  450 + */
  451 + this.parseJSON = function(data) {
  452 + // Attempt to parse using the native JSON parser first
  453 + if (window.JSON && window.JSON.parse) {
  454 + return window.JSON.parse(data);
  455 + }
  456 +
  457 + //var rx_one = /^[\],:{}\s]*$/,
  458 + // rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
  459 + // rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
  460 + // rx_four = /(?:^|:|,)(?:\s*\[)+/g,
  461 + var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  462 +
  463 + //var json;
  464 +
  465 + var text = String(data);
  466 + rx_dangerous.lastIndex = 0;
  467 + if(rx_dangerous.test(text)){
  468 + text = text.replace(rx_dangerous, function(a){
  469 + return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  470 + });
  471 + }
  472 +
  473 + // todo 使用一下判断,增加安全性
  474 + //if (
  475 + // rx_one.test(
  476 + // text
  477 + // .replace(rx_two, '@')
  478 + // .replace(rx_three, ']')
  479 + // .replace(rx_four, '')
  480 + // )
  481 + //) {
  482 + // return eval('(' + text + ')');
  483 + //}
  484 +
  485 + return eval('('+text+')');
  486 + };
  487 +
  488 + /**
  489 + * parse javascript object to json string
  490 + * @param {Object} object
  491 + * @return {String} json string
  492 + */
  493 + this.stringifyJSON = function(obj) {
  494 + // Attempt to parse using the native JSON parser first
  495 + if (window.JSON && window.JSON.stringify) {
  496 + return window.JSON.stringify(obj);
  497 + }
  498 + switch (typeof (obj)) {
  499 + case 'string':
  500 + return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
  501 + case 'array':
  502 + return '[' + obj.map(that.stringifyJSON).join(',') + ']';
  503 + case 'object':
  504 + if (obj instanceof Array) {
  505 + var strArr = [];
  506 + var len = obj.length;
  507 + for (var i = 0; i < len; i++) {
  508 + strArr.push(that.stringifyJSON(obj[i]));
  509 + }
  510 + return '[' + strArr.join(',') + ']';
  511 + } else if (obj === null) {
  512 + return 'null';
  513 + } else {
  514 + var string = [];
  515 + for (var property in obj) {
  516 + if (obj.hasOwnProperty(property)) {
  517 + string.push(that.stringifyJSON(property) + ':' + that.stringifyJSON(obj[property]));
  518 + }
  519 + }
  520 + return '{' + string.join(',') + '}';
  521 + }
  522 + break;
  523 + case 'number':
  524 + return obj;
  525 + case false:
  526 + return obj;
  527 + case 'boolean':
  528 + return obj;
  529 + }
  530 + };
  531 +
  532 + /**
  533 + * trim space beside text
  534 + * @param {String} untrimed string
  535 + * @return {String} trimed string
  536 + */
  537 + this.trim = function(text) {
  538 + return text === null ? "" : text.replace(/^\s+|\s+$/g, '');
  539 + };
  540 +
  541 + /**
  542 + * create a uploader by QiniuJsSDK
  543 + * @param {object} options to create a new uploader
  544 + * @return {object} uploader
  545 + */
  546 + this.uploader = function(op) {
  547 +
  548 + /********** inner function define start **********/
  549 +
  550 + // according the different condition to reset chunk size
  551 + // and the upload strategy according with the chunk size
  552 + // when chunk size is zero will cause to direct upload
  553 + // see the statement binded on 'BeforeUpload' event
  554 + var reset_chunk_size = function() {
  555 + var ie = that.detectIEVersion();
  556 + var BLOCK_BITS, MAX_CHUNK_SIZE, chunk_size;
  557 + // case Safari 5、Windows 7、iOS 7 set isSpecialSafari to true
  558 + var isSpecialSafari = (mOxie.Env.browser === "Safari" && mOxie.Env.version <= 5 && mOxie.Env.os === "Windows" && mOxie.Env.osVersion === "7") || (mOxie.Env.browser === "Safari" && mOxie.Env.os === "iOS" && mOxie.Env.osVersion === "7");
  559 + // case IE 9-,chunk_size is not empty and flash is included in runtimes
  560 + // set op.chunk_size to zero
  561 + //if (ie && ie < 9 && op.chunk_size && op.runtimes.indexOf('flash') >= 0) {
  562 + if (ie && ie < 9 && op.chunk_size && op.runtimes.indexOf('flash') >= 0) {
  563 + // link: http://www.plupload.com/docs/Frequently-Asked-Questions#when-to-use-chunking-and-when-not
  564 + // when plupload chunk_size setting is't null ,it cause bug in ie8/9 which runs flash runtimes (not support html5) .
  565 + op.chunk_size = 0;
  566 + } else if (isSpecialSafari) {
  567 + // win7 safari / iOS7 safari have bug when in chunk upload mode
  568 + // reset chunk_size to 0
  569 + // disable chunk in special version safari
  570 + op.chunk_size = 0;
  571 + } else {
  572 + BLOCK_BITS = 20;
  573 + MAX_CHUNK_SIZE = 4 << BLOCK_BITS; //4M
  574 +
  575 + chunk_size = plupload.parseSize(op.chunk_size);
  576 + if (chunk_size > MAX_CHUNK_SIZE) {
  577 + op.chunk_size = MAX_CHUNK_SIZE;
  578 + }
  579 + // qiniu service max_chunk_size is 4m
  580 + // reset chunk_size to max_chunk_size(4m) when chunk_size > 4m
  581 + }
  582 + // if op.chunk_size set 0 will be cause to direct upload
  583 + };
  584 +
  585 + var getHosts = function(hosts) {
  586 + var result = [];
  587 + for (var i = 0; i < hosts.length; i++) {
  588 + var host = hosts[i];
  589 + if (host.indexOf('-H') === 0) {
  590 + result.push(host.split(' ')[2]);
  591 + } else {
  592 + result.push(host);
  593 + }
  594 + }
  595 + return result;
  596 + };
  597 +
  598 + var getPutPolicy = function (uptoken) {
  599 + var segments = uptoken.split(":");
  600 + var ak = segments[0];
  601 + var putPolicy = that.parseJSON(that.URLSafeBase64Decode(segments[2]));
  602 + putPolicy.ak = ak;
  603 + if (putPolicy.scope.indexOf(":") >= 0) {
  604 + putPolicy.bucket = putPolicy.scope.split(":")[0];
  605 + putPolicy.key = putPolicy.scope.split(":")[1];
  606 + } else {
  607 + putPolicy.bucket = putPolicy.scope;
  608 + }
  609 + return putPolicy;
  610 + };
  611 +
  612 + var getUpHosts = function(uptoken) {
  613 + var putPolicy = getPutPolicy(uptoken);
  614 + // var uphosts_url = "//uc.qbox.me/v1/query?ak="+ak+"&bucket="+putPolicy.scope;
  615 + // IE 9- is not support protocal relative url
  616 + var uphosts_url = window.location.protocol + "//uc.qbox.me/v1/query?ak=" + putPolicy.ak + "&bucket=" + putPolicy.bucket;
  617 + logger.debug("putPolicy: ", putPolicy);
  618 + logger.debug("get uphosts from: ", uphosts_url);
  619 + var ie = that.detectIEVersion();
  620 + var ajax;
  621 + if (ie && ie <= 9) {
  622 + ajax = new mOxie.XMLHttpRequest();
  623 + mOxie.Env.swf_url = op.flash_swf_url;
  624 + }else{
  625 + ajax = that.createAjax();
  626 + }
  627 + ajax.open('GET', uphosts_url, false);
  628 + var onreadystatechange = function(){
  629 + logger.debug("ajax.readyState: ", ajax.readyState);
  630 + if (ajax.readyState === 4) {
  631 + logger.debug("ajax.status: ", ajax.status);
  632 + if (ajax.status < 400) {
  633 + var res = that.parseJSON(ajax.responseText);
  634 + qiniuUpHosts.http = getHosts(res.http.up);
  635 + qiniuUpHosts.https = getHosts(res.https.up);
  636 + logger.debug("get new uphosts: ", qiniuUpHosts);
  637 + that.resetUploadUrl();
  638 + } else {
  639 + logger.error("get uphosts error: ", ajax.responseText);
  640 + }
  641 + }
  642 + };
  643 + if (ie && ie <= 9) {
  644 + ajax.bind('readystatechange', onreadystatechange);
  645 + }else{
  646 + ajax.onreadystatechange = onreadystatechange;
  647 + }
  648 + ajax.send();
  649 + // ajax.send();
  650 + // if (ajax.status < 400) {
  651 + // var res = that.parseJSON(ajax.responseText);
  652 + // qiniuUpHosts.http = getHosts(res.http.up);
  653 + // qiniuUpHosts.https = getHosts(res.https.up);
  654 + // logger.debug("get new uphosts: ", qiniuUpHosts);
  655 + // that.resetUploadUrl();
  656 + // } else {
  657 + // logger.error("get uphosts error: ", ajax.responseText);
  658 + // }
  659 + return;
  660 + };
  661 +
  662 + var getUptoken = function(file) {
  663 + if (!that.token || (op.uptoken_url && that.tokenInfo.isExpired())) {
  664 + return getNewUpToken(file);
  665 + } else {
  666 + return that.token;
  667 + }
  668 + };
  669 +
  670 + // getNewUptoken maybe called at Init Event or BeforeUpload Event
  671 + // case Init Event, the file param of getUptken will be set a null value
  672 + // if op.uptoken has value, set uptoken with op.uptoken
  673 + // else if op.uptoken_url has value, set uptoken from op.uptoken_url
  674 + // else if op.uptoken_func has value, set uptoken by result of op.uptoken_func
  675 + var getNewUpToken = function(file) {
  676 + if (op.uptoken) {
  677 + that.token = op.uptoken;
  678 + } else if (op.uptoken_url) {
  679 + logger.debug("get uptoken from: ", that.uptoken_url);
  680 + // TODO: use mOxie
  681 + var ajax = that.createAjax();
  682 + ajax.open('GET', that.uptoken_url, false);
  683 + ajax.setRequestHeader("If-Modified-Since", "0");
  684 + // ajax.onreadystatechange = function() {
  685 + // if (ajax.readyState === 4 && ajax.status === 200) {
  686 + // var res = that.parseJSON(ajax.responseText);
  687 + // that.token = res.uptoken;
  688 + // }
  689 + // };
  690 + ajax.send();
  691 + if (ajax.status === 200) {
  692 + var res = that.parseJSON(ajax.responseText);
  693 + that.token = res.uptoken;
  694 + var segments = that.token.split(":");
  695 + var putPolicy = that.parseJSON(that.URLSafeBase64Decode(segments[2]));
  696 + if (!that.tokenMap) {
  697 + that.tokenMap = {};
  698 + }
  699 + var getTimestamp = function(time) {
  700 + return Math.ceil(time.getTime()/1000);
  701 + };
  702 + var serverTime = getTimestamp(new Date(ajax.getResponseHeader("date")));
  703 + var clientTime = getTimestamp(new Date());
  704 + that.tokenInfo = {
  705 + serverDelay: clientTime - serverTime,
  706 + deadline: putPolicy.deadline,
  707 + isExpired: function() {
  708 + var leftTime = this.deadline - getTimestamp(new Date()) + this.serverDelay;
  709 + return leftTime < 600;
  710 + }
  711 + };
  712 + logger.debug("get new uptoken: ", that.token);
  713 + logger.debug("get token info: ", that.tokenInfo);
  714 + } else {
  715 + logger.error("get uptoken error: ", ajax.responseText);
  716 + }
  717 + } else if (op.uptoken_func) {
  718 + logger.debug("get uptoken from uptoken_func");
  719 + that.token = op.uptoken_func(file);
  720 + logger.debug("get new uptoken: ", that.token);
  721 + } else {
  722 + logger.error("one of [uptoken, uptoken_url, uptoken_func] settings in options is required!");
  723 + }
  724 + if (that.token) {
  725 + getUpHosts(that.token);
  726 + }
  727 + return that.token;
  728 + };
  729 +
  730 + // get file key according with the user passed options
  731 + var getFileKey = function(up, file, func) {
  732 + // WARNING
  733 + // When you set the key in putPolicy by "scope": "bucket:key"
  734 + // You should understand the risk of override a file in the bucket
  735 + // So the code below that automatically get key from uptoken has been commented
  736 + // var putPolicy = getPutPolicy(that.token)
  737 + // if (putPolicy.key) {
  738 + // logger.debug("key is defined in putPolicy.scope: ", putPolicy.key)
  739 + // return putPolicy.key
  740 + // }
  741 + var key = '',
  742 + unique_names = false;
  743 + if (!op.save_key) {
  744 + unique_names = up.getOption && up.getOption('unique_names');
  745 + unique_names = unique_names || (up.settings && up.settings.unique_names);
  746 + if (unique_names) {
  747 + var ext = that.getFileExtension(file.name);
  748 + key = ext ? file.id + '.' + ext : file.id;
  749 + } else if (typeof func === 'function') {
  750 + key = func(up, file);
  751 + } else {
  752 + key = file.name;
  753 + }
  754 + }
  755 + return key;
  756 + };
  757 +
  758 + /********** inner function define end **********/
  759 +
  760 + if (op.log_level) {
  761 + logger.level = op.log_level;
  762 + }
  763 +
  764 + if (!op.domain) {
  765 + throw 'domain setting in options is required!';
  766 + }
  767 +
  768 + if (!op.browse_button) {
  769 + throw 'browse_button setting in options is required!';
  770 + }
  771 +
  772 + if (!op.uptoken && !op.uptoken_url && !op.uptoken_func) {
  773 + throw 'one of [uptoken, uptoken_url, uptoken_func] settings in options is required!';
  774 + }
  775 +
  776 + logger.debug("init uploader start");
  777 +
  778 + logger.debug("environment: ", mOxie.Env);
  779 +
  780 + logger.debug("userAgent: ", navigator.userAgent);
  781 +
  782 + var option = {};
  783 +
  784 + // hold the handler from user passed options
  785 + var _Error_Handler = op.init && op.init.Error;
  786 + var _FileUploaded_Handler = op.init && op.init.FileUploaded;
  787 +
  788 + // replace the handler for intercept
  789 + op.init.Error = function() {};
  790 + op.init.FileUploaded = function() {};
  791 +
  792 + that.uptoken_url = op.uptoken_url;
  793 + that.token = '';
  794 + that.key_handler = typeof op.init.Key === 'function' ? op.init.Key : '';
  795 + this.domain = op.domain;
  796 + // TODO: ctx is global in scope of a uploader instance
  797 + // this maybe cause error
  798 + var ctx = '';
  799 + var speedCalInfo = {
  800 + isResumeUpload: false,
  801 + resumeFilesize: 0,
  802 + startTime: '',
  803 + currentTime: ''
  804 + };
  805 +
  806 + reset_chunk_size();
  807 + logger.debug("invoke reset_chunk_size()");
  808 + logger.debug("op.chunk_size: ", op.chunk_size);
  809 +
  810 + var defaultSetting = {
  811 + url: qiniuUploadUrl,
  812 + multipart_params: {
  813 + token: ''
  814 + }
  815 + };
  816 + var ie = that.detectIEVersion();
  817 + // case IE 9-
  818 + // add accept in multipart params
  819 + if (ie && ie <= 9) {
  820 + defaultSetting.multipart_params.accept = 'text/plain; charset=utf-8';
  821 + logger.debug("add accept text/plain in multipart params");
  822 + }
  823 +
  824 + // compose options with user passed options and default setting
  825 + plupload.extend(option, op, defaultSetting);
  826 +
  827 + logger.debug("option: ", option);
  828 +
  829 + // create a new uploader with composed options
  830 + var uploader = new plupload.Uploader(option);
  831 +
  832 + logger.debug("new plupload.Uploader(option)");
  833 +
  834 + // bind getNewUpToken to 'Init' event
  835 + uploader.bind('Init', function(up, params) {
  836 + logger.debug("Init event activated");
  837 + // if op.get_new_uptoken is not true
  838 + // invoke getNewUptoken when uploader init
  839 + // else
  840 + // getNewUptoken everytime before a new file upload
  841 + if(!op.get_new_uptoken){
  842 + getNewUpToken(null);
  843 + }
  844 + //getNewUpToken(null);
  845 + });
  846 +
  847 + logger.debug("bind Init event");
  848 +
  849 + // bind 'FilesAdded' event
  850 + // when file be added and auto_start has set value
  851 + // uploader will auto start upload the file
  852 + uploader.bind('FilesAdded', function(up, files) {
  853 + logger.debug("FilesAdded event activated");
  854 + var auto_start = up.getOption && up.getOption('auto_start');
  855 + auto_start = auto_start || (up.settings && up.settings.auto_start);
  856 + logger.debug("auto_start: ", auto_start);
  857 + logger.debug("files: ", files);
  858 +
  859 + // detect is iOS
  860 + var is_ios = function (){
  861 + if(mOxie.Env.OS.toLowerCase()==="ios") {
  862 + return true;
  863 + } else {
  864 + return false;
  865 + }
  866 + };
  867 +
  868 + // if current env os is iOS change file name to [time].[ext]
  869 + if (is_ios()) {
  870 + for (var i = 0; i < files.length; i++) {
  871 + var file = files[i];
  872 + var ext = that.getFileExtension(file.name);
  873 + file.name = file.id + "." + ext;
  874 + }
  875 + }
  876 +
  877 + if (auto_start) {
  878 + setTimeout(function(){
  879 + up.start();
  880 + logger.debug("invoke up.start()");
  881 + }, 0);
  882 + // up.start();
  883 + // plupload.each(files, function(i, file) {
  884 + // up.start();
  885 + // logger.debug("invoke up.start()")
  886 + // logger.debug("file: ", file);
  887 + // });
  888 + }
  889 + up.refresh(); // Reposition Flash/Silverlight
  890 + });
  891 +
  892 + logger.debug("bind FilesAdded event");
  893 +
  894 + // bind 'BeforeUpload' event
  895 + // intercept the process of upload
  896 + // - prepare uptoken
  897 + // - according the chunk size to make differnt upload strategy
  898 + // - resume upload with the last breakpoint of file
  899 + uploader.bind('BeforeUpload', function(up, file) {
  900 + logger.debug("BeforeUpload event activated");
  901 + // add a key named speed for file object
  902 + file.speed = file.speed || 0;
  903 + ctx = '';
  904 +
  905 + if(op.get_new_uptoken){
  906 + getNewUpToken(file);
  907 + }
  908 +
  909 + var directUpload = function(up, file, func) {
  910 + speedCalInfo.startTime = new Date().getTime();
  911 + var multipart_params_obj;
  912 + if (op.save_key) {
  913 + multipart_params_obj = {
  914 + 'token': that.token
  915 + };
  916 + } else {
  917 + multipart_params_obj = {
  918 + 'key': getFileKey(up, file, func),
  919 + 'token': that.token
  920 + };
  921 + }
  922 + var ie = that.detectIEVersion();
  923 + // case IE 9-
  924 + // add accept in multipart params
  925 + if (ie && ie <= 9) {
  926 + multipart_params_obj.accept = 'text/plain; charset=utf-8';
  927 + logger.debug("add accept text/plain in multipart params");
  928 + }
  929 +
  930 + logger.debug("directUpload multipart_params_obj: ", multipart_params_obj);
  931 +
  932 + var x_vars = op.x_vars;
  933 + if (x_vars !== undefined && typeof x_vars === 'object') {
  934 + for (var x_key in x_vars) {
  935 + if (x_vars.hasOwnProperty(x_key)) {
  936 + if (typeof x_vars[x_key] === 'function') {
  937 + multipart_params_obj['x:' + x_key] = x_vars[x_key](up, file);
  938 + } else if (typeof x_vars[x_key] !== 'object') {
  939 + multipart_params_obj['x:' + x_key] = x_vars[x_key];
  940 + }
  941 + }
  942 + }
  943 + }
  944 +
  945 + up.setOption({
  946 + 'url': qiniuUploadUrl,
  947 + 'multipart': true,
  948 + 'chunk_size': is_android_weixin_or_qq() ? op.max_file_size : undefined,
  949 + 'multipart_params': multipart_params_obj
  950 + });
  951 + };
  952 +
  953 + // detect is weixin or qq inner browser
  954 + var is_android_weixin_or_qq = function (){
  955 + var ua = navigator.userAgent.toLowerCase();
  956 + if((ua.match(/MicroMessenger/i) || mOxie.Env.browser === "QQBrowser" || ua.match(/V1_AND_SQ/i)) && mOxie.Env.OS.toLowerCase()==="android") {
  957 + return true;
  958 + } else {
  959 + return false;
  960 + }
  961 + };
  962 +
  963 + var chunk_size = up.getOption && up.getOption('chunk_size');
  964 + chunk_size = chunk_size || (up.settings && up.settings.chunk_size);
  965 +
  966 + logger.debug("uploader.runtime: ",uploader.runtime);
  967 + logger.debug("chunk_size: ",chunk_size);
  968 +
  969 + // TODO: flash support chunk upload
  970 + if ((uploader.runtime === 'html5' || uploader.runtime === 'flash') && chunk_size) {
  971 + if (file.size < chunk_size || is_android_weixin_or_qq()) {
  972 + logger.debug("directUpload because file.size < chunk_size || is_android_weixin_or_qq()");
  973 + // direct upload if file size is less then the chunk size
  974 + directUpload(up, file, that.key_handler);
  975 + } else {
  976 + // TODO: need a polifill to make it work in IE 9-
  977 + // ISSUE: if file.name is existed in localStorage
  978 + // but not the same file maybe cause error
  979 + var localFileInfo = localStorage.getItem(file.name);
  980 + var blockSize = chunk_size;
  981 + if (localFileInfo) {
  982 + // TODO: although only the html5 runtime will enter this statement
  983 + // but need uniform way to make convertion between string and json
  984 + localFileInfo = that.parseJSON(localFileInfo);
  985 + var now = (new Date()).getTime();
  986 + var before = localFileInfo.time || 0;
  987 + var aDay = 24 * 60 * 60 * 1000; // milliseconds of one day
  988 + // if the last upload time is within one day
  989 + // will upload continuously follow the last breakpoint
  990 + // else
  991 + // will reupload entire file
  992 + if (now - before < aDay) {
  993 +
  994 + if (localFileInfo.percent !== 100) {
  995 + if (file.size === localFileInfo.total) {
  996 + // TODO: if file.name and file.size is the same
  997 + // but not the same file will cause error
  998 + file.percent = localFileInfo.percent;
  999 + file.loaded = localFileInfo.offset;
  1000 + ctx = localFileInfo.ctx;
  1001 +
  1002 + // set speed info
  1003 + speedCalInfo.isResumeUpload = true;
  1004 + speedCalInfo.resumeFilesize = localFileInfo.offset;
  1005 +
  1006 + // set block size
  1007 + if (localFileInfo.offset + blockSize > file.size) {
  1008 + blockSize = file.size - localFileInfo.offset;
  1009 + }
  1010 + } else {
  1011 + // remove file info when file.size is conflict with file info
  1012 + localStorage.removeItem(file.name);
  1013 + }
  1014 +
  1015 + } else {
  1016 + // remove file info when upload percent is 100%
  1017 + // avoid 499 bug
  1018 + localStorage.removeItem(file.name);
  1019 + }
  1020 + } else {
  1021 + // remove file info when last upload time is over one day
  1022 + localStorage.removeItem(file.name);
  1023 + }
  1024 + }
  1025 + speedCalInfo.startTime = new Date().getTime();
  1026 + var multipart_params_obj = {};
  1027 + var ie = that.detectIEVersion();
  1028 + // case IE 9-
  1029 + // add accept in multipart params
  1030 + if (ie && ie <= 9) {
  1031 + multipart_params_obj.accept = 'text/plain; charset=utf-8';
  1032 + logger.debug("add accept text/plain in multipart params");
  1033 + }
  1034 + // TODO: to support bput
  1035 + // http://developer.qiniu.com/docs/v6/api/reference/up/bput.html
  1036 + up.setOption({
  1037 + 'url': qiniuUploadUrl + '/mkblk/' + blockSize,
  1038 + 'multipart': false,
  1039 + 'chunk_size': chunk_size,
  1040 + 'required_features': "chunks",
  1041 + 'headers': {
  1042 + 'Authorization': 'UpToken ' + getUptoken(file)
  1043 + },
  1044 + 'multipart_params': multipart_params_obj
  1045 + });
  1046 + }
  1047 + } else {
  1048 + logger.debug("directUpload because uploader.runtime !== 'html5' || uploader.runtime !== 'flash' || !chunk_size");
  1049 + // direct upload if runtime is not html5
  1050 + directUpload(up, file, that.key_handler);
  1051 + }
  1052 + });
  1053 +
  1054 + logger.debug("bind BeforeUpload event");
  1055 +
  1056 + // bind 'UploadProgress' event
  1057 + // calculate upload speed
  1058 + uploader.bind('UploadProgress', function(up, file) {
  1059 + logger.trace("UploadProgress event activated");
  1060 + speedCalInfo.currentTime = new Date().getTime();
  1061 + var timeUsed = speedCalInfo.currentTime - speedCalInfo.startTime; // ms
  1062 + var fileUploaded = file.loaded || 0;
  1063 + if (speedCalInfo.isResumeUpload) {
  1064 + fileUploaded = file.loaded - speedCalInfo.resumeFilesize;
  1065 + }
  1066 + file.speed = (fileUploaded / timeUsed * 1000).toFixed(0) || 0; // unit: byte/s
  1067 + });
  1068 +
  1069 + logger.debug("bind UploadProgress event");
  1070 +
  1071 + // bind 'ChunkUploaded' event
  1072 + // store the chunk upload info and set next chunk upload url
  1073 + uploader.bind('ChunkUploaded', function(up, file, info) {
  1074 + logger.debug("ChunkUploaded event activated");
  1075 + logger.debug("file: ", file);
  1076 + logger.debug("info: ", info);
  1077 + var res = that.parseJSON(info.response);
  1078 + logger.debug("res: ", res);
  1079 + // ctx should look like '[chunk01_ctx],[chunk02_ctx],[chunk03_ctx],...'
  1080 + ctx = ctx ? ctx + ',' + res.ctx : res.ctx;
  1081 + var leftSize = info.total - info.offset;
  1082 + var chunk_size = up.getOption && up.getOption('chunk_size');
  1083 + chunk_size = chunk_size || (up.settings && up.settings.chunk_size);
  1084 + if (leftSize < chunk_size) {
  1085 + up.setOption({
  1086 + 'url': qiniuUploadUrl + '/mkblk/' + leftSize
  1087 + });
  1088 + logger.debug("up.setOption url: ", qiniuUploadUrl + '/mkblk/' + leftSize);
  1089 + }
  1090 + up.setOption({
  1091 + 'headers': {
  1092 + 'Authorization': 'UpToken ' + getUptoken(file)
  1093 + }
  1094 + });
  1095 + localStorage.setItem(file.name, that.stringifyJSON({
  1096 + ctx: ctx,
  1097 + percent: file.percent,
  1098 + total: info.total,
  1099 + offset: info.offset,
  1100 + time: (new Date()).getTime()
  1101 + }));
  1102 + });
  1103 +
  1104 + logger.debug("bind ChunkUploaded event");
  1105 +
  1106 + var retries = qiniuUploadUrls.length;
  1107 +
  1108 + // if error is unkown switch upload url and retry
  1109 + var unknow_error_retry = function(file){
  1110 + if (retries-- > 0) {
  1111 + setTimeout(function(){
  1112 + that.resetUploadUrl();
  1113 + file.status = plupload.QUEUED;
  1114 + uploader.stop();
  1115 + uploader.start();
  1116 + }, 0);
  1117 + return true;
  1118 + }else{
  1119 + retries = qiniuUploadUrls.length;
  1120 + return false;
  1121 + }
  1122 + };
  1123 +
  1124 + // bind 'Error' event
  1125 + // check the err.code and return the errTip
  1126 + uploader.bind('Error', (function(_Error_Handler) {
  1127 + return function(up, err) {
  1128 + logger.error("Error event activated");
  1129 + logger.error("err: ", err);
  1130 + var errTip = '';
  1131 + var file = err.file;
  1132 + if (file) {
  1133 + switch (err.code) {
  1134 + case plupload.FAILED:
  1135 + errTip = '上传失败。请稍后再试。';
  1136 + break;
  1137 + case plupload.FILE_SIZE_ERROR:
  1138 + var max_file_size = up.getOption && up.getOption('max_file_size');
  1139 + max_file_size = max_file_size || (up.settings && up.settings.max_file_size);
  1140 + errTip = '浏览器最大可上传' + max_file_size + '。更大文件请使用命令行工具。';
  1141 + break;
  1142 + case plupload.FILE_EXTENSION_ERROR:
  1143 + errTip = '文件验证失败。请稍后重试。';
  1144 + break;
  1145 + case plupload.HTTP_ERROR:
  1146 + if (err.response === '') {
  1147 + // Fix parseJSON error ,when http error is like net::ERR_ADDRESS_UNREACHABLE
  1148 + errTip = err.message || '未知网络错误。';
  1149 + if (!unknow_error_retry(file)) {
  1150 + return;
  1151 + }
  1152 + break;
  1153 + }
  1154 + var errorObj = that.parseJSON(err.response);
  1155 + var errorText = errorObj.error;
  1156 + switch (err.status) {
  1157 + case 400:
  1158 + errTip = "请求报文格式错误。";
  1159 + break;
  1160 + case 401:
  1161 + errTip = "客户端认证授权失败。请重试或提交反馈。";
  1162 + break;
  1163 + case 405:
  1164 + errTip = "客户端请求错误。请重试或提交反馈。";
  1165 + break;
  1166 + case 579:
  1167 + errTip = "资源上传成功,但回调失败。";
  1168 + break;
  1169 + case 599:
  1170 + errTip = "网络连接异常。请重试或提交反馈。";
  1171 + if (!unknow_error_retry(file)) {
  1172 + return;
  1173 + }
  1174 + break;
  1175 + case 614:
  1176 + errTip = "文件已存在。";
  1177 + try {
  1178 + errorObj = that.parseJSON(errorObj.error);
  1179 + errorText = errorObj.error || 'file exists';
  1180 + } catch (e) {
  1181 + errorText = errorObj.error || 'file exists';
  1182 + }
  1183 + break;
  1184 + case 631:
  1185 + errTip = "指定空间不存在。";
  1186 + break;
  1187 + case 701:
  1188 + errTip = "上传数据块校验出错。请重试或提交反馈。";
  1189 + break;
  1190 + default:
  1191 + errTip = "未知错误。";
  1192 + if (!unknow_error_retry(file)) {
  1193 + return;
  1194 + }
  1195 + break;
  1196 + }
  1197 + errTip = errTip + '(' + err.status + ':' + errorText + ')';
  1198 + break;
  1199 + case plupload.SECURITY_ERROR:
  1200 + errTip = '安全配置错误。请联系网站管理员。';
  1201 + break;
  1202 + case plupload.GENERIC_ERROR:
  1203 + errTip = '上传失败。请稍后再试。';
  1204 + break;
  1205 + case plupload.IO_ERROR:
  1206 + errTip = '上传失败。请稍后再试。';
  1207 + break;
  1208 + case plupload.INIT_ERROR:
  1209 + errTip = '网站配置错误。请联系网站管理员。';
  1210 + uploader.destroy();
  1211 + break;
  1212 + default:
  1213 + errTip = err.message + err.details;
  1214 + if (!unknow_error_retry(file)) {
  1215 + return;
  1216 + }
  1217 + break;
  1218 + }
  1219 + if (_Error_Handler) {
  1220 + _Error_Handler(up, err, errTip);
  1221 + }
  1222 + }
  1223 + up.refresh(); // Reposition Flash/Silverlight
  1224 + };
  1225 + })(_Error_Handler));
  1226 +
  1227 + logger.debug("bind Error event");
  1228 +
  1229 + // bind 'FileUploaded' event
  1230 + // intercept the complete of upload
  1231 + // - get downtoken from downtoken_url if bucket is private
  1232 + // - invoke mkfile api to compose chunks if upload strategy is chunk upload
  1233 + uploader.bind('FileUploaded', (function(_FileUploaded_Handler) {
  1234 + return function(up, file, info) {
  1235 + logger.debug("FileUploaded event activated");
  1236 + logger.debug("file: ", file);
  1237 + logger.debug("info: ", info);
  1238 + var last_step = function(up, file, info) {
  1239 + if (op.downtoken_url) {
  1240 + // if op.dowontoken_url is not empty
  1241 + // need get downtoken before invoke the _FileUploaded_Handler
  1242 + var ajax_downtoken = that.createAjax();
  1243 + ajax_downtoken.open('POST', op.downtoken_url, true);
  1244 + ajax_downtoken.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  1245 + ajax_downtoken.onreadystatechange = function() {
  1246 + if (ajax_downtoken.readyState === 4) {
  1247 + if (ajax_downtoken.status === 200) {
  1248 + var res_downtoken;
  1249 + try {
  1250 + res_downtoken = that.parseJSON(ajax_downtoken.responseText);
  1251 + } catch (e) {
  1252 + throw ('invalid json format');
  1253 + }
  1254 + var info_extended = {};
  1255 + plupload.extend(info_extended, that.parseJSON(info), res_downtoken);
  1256 + if (_FileUploaded_Handler) {
  1257 + _FileUploaded_Handler(up, file, that.stringifyJSON(info_extended));
  1258 + }
  1259 + } else {
  1260 + uploader.trigger('Error', {
  1261 + status: ajax_downtoken.status,
  1262 + response: ajax_downtoken.responseText,
  1263 + file: file,
  1264 + code: plupload.HTTP_ERROR
  1265 + });
  1266 + }
  1267 + }
  1268 + };
  1269 + ajax_downtoken.send('key=' + that.parseJSON(info).key + '&domain=' + op.domain);
  1270 + } else if (_FileUploaded_Handler) {
  1271 + _FileUploaded_Handler(up, file, info);
  1272 + }
  1273 + };
  1274 +
  1275 + var res = that.parseJSON(info.response);
  1276 + ctx = ctx ? ctx : res.ctx;
  1277 + // if ctx is not empty
  1278 + // that means the upload strategy is chunk upload
  1279 + // befroe the invoke the last_step
  1280 + // we need request the mkfile to compose all uploaded chunks
  1281 + // else
  1282 + // invalke the last_step
  1283 + logger.debug("ctx: ", ctx);
  1284 + if (ctx) {
  1285 + var key = '';
  1286 + logger.debug("save_key: ", op.save_key);
  1287 + if (!op.save_key) {
  1288 + key = getFileKey(up, file, that.key_handler);
  1289 + key = key ? '/key/' + that.URLSafeBase64Encode(key) : '';
  1290 + }
  1291 +
  1292 + var fname = '/fname/' + that.URLSafeBase64Encode(file.name);
  1293 +
  1294 + logger.debug("op.x_vars: ", op.x_vars);
  1295 + var x_vars = op.x_vars,
  1296 + x_val = '',
  1297 + x_vars_url = '';
  1298 + if (x_vars !== undefined && typeof x_vars === 'object') {
  1299 + for (var x_key in x_vars) {
  1300 + if (x_vars.hasOwnProperty(x_key)) {
  1301 + if (typeof x_vars[x_key] === 'function') {
  1302 + x_val = that.URLSafeBase64Encode(x_vars[x_key](up, file));
  1303 + } else if (typeof x_vars[x_key] !== 'object') {
  1304 + x_val = that.URLSafeBase64Encode(x_vars[x_key]);
  1305 + }
  1306 + x_vars_url += '/x:' + x_key + '/' + x_val;
  1307 + }
  1308 + }
  1309 + }
  1310 +
  1311 + var url = qiniuUploadUrl + '/mkfile/' + file.size + key + fname + x_vars_url;
  1312 +
  1313 + var ie = that.detectIEVersion();
  1314 + var ajax;
  1315 + if (ie && ie <= 9) {
  1316 + ajax = new mOxie.XMLHttpRequest();
  1317 + mOxie.Env.swf_url = op.flash_swf_url;
  1318 + }else{
  1319 + ajax = that.createAjax();
  1320 + }
  1321 + ajax.open('POST', url, true);
  1322 + ajax.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
  1323 + ajax.setRequestHeader('Authorization', 'UpToken ' + that.token);
  1324 + var onreadystatechange = function(){
  1325 + logger.debug("ajax.readyState: ", ajax.readyState);
  1326 + if (ajax.readyState === 4) {
  1327 + localStorage.removeItem(file.name);
  1328 + var info;
  1329 + if (ajax.status === 200) {
  1330 + info = ajax.responseText;
  1331 + logger.debug("mkfile is success: ", info);
  1332 + last_step(up, file, info);
  1333 + } else {
  1334 + info = {
  1335 + status: ajax.status,
  1336 + response: ajax.responseText,
  1337 + file: file,
  1338 + code: -200,
  1339 + responseHeaders: ajax.getAllResponseHeaders()
  1340 + };
  1341 + logger.debug("mkfile is error: ", info);
  1342 + uploader.trigger('Error', info);
  1343 + }
  1344 + }
  1345 + };
  1346 + if (ie && ie <= 9) {
  1347 + ajax.bind('readystatechange', onreadystatechange);
  1348 + }else{
  1349 + ajax.onreadystatechange = onreadystatechange;
  1350 + }
  1351 + ajax.send(ctx);
  1352 + logger.debug("mkfile: ", url);
  1353 + } else {
  1354 + last_step(up, file, info.response);
  1355 + }
  1356 +
  1357 + };
  1358 + })(_FileUploaded_Handler));
  1359 +
  1360 + logger.debug("bind FileUploaded event");
  1361 +
  1362 + // init uploader
  1363 + uploader.init();
  1364 +
  1365 + logger.debug("invoke uploader.init()");
  1366 +
  1367 + logger.debug("init uploader end");
  1368 +
  1369 + return uploader;
  1370 + };
  1371 +
  1372 + /**
  1373 + * get url by key
  1374 + * @param {String} key of file
  1375 + * @return {String} url of file
  1376 + */
  1377 + this.getUrl = function(key) {
  1378 + if (!key) {
  1379 + return false;
  1380 + }
  1381 + key = encodeURI(key);
  1382 + var domain = this.domain;
  1383 + if (domain.slice(domain.length - 1) !== '/') {
  1384 + domain = domain + '/';
  1385 + }
  1386 + return domain + key;
  1387 + };
  1388 +
  1389 + /**
  1390 + * invoke the imageView2 api of Qiniu
  1391 + * @param {Object} api params
  1392 + * @param {String} key of file
  1393 + * @return {String} url of processed image
  1394 + */
  1395 + this.imageView2 = function(op, key) {
  1396 +
  1397 + if (!/^\d$/.test(op.mode)) {
  1398 + return false;
  1399 + }
  1400 +
  1401 + var mode = op.mode,
  1402 + w = op.w || '',
  1403 + h = op.h || '',
  1404 + q = op.q || '',
  1405 + format = op.format || '';
  1406 +
  1407 + if (!w && !h) {
  1408 + return false;
  1409 + }
  1410 +
  1411 + var imageUrl = 'imageView2/' + mode;
  1412 + imageUrl += w ? '/w/' + w : '';
  1413 + imageUrl += h ? '/h/' + h : '';
  1414 + imageUrl += q ? '/q/' + q : '';
  1415 + imageUrl += format ? '/format/' + format : '';
  1416 + if (key) {
  1417 + imageUrl = this.getUrl(key) + '?' + imageUrl;
  1418 + }
  1419 + return imageUrl;
  1420 + };
  1421 +
  1422 + /**
  1423 + * invoke the imageMogr2 api of Qiniu
  1424 + * @param {Object} api params
  1425 + * @param {String} key of file
  1426 + * @return {String} url of processed image
  1427 + */
  1428 + this.imageMogr2 = function(op, key) {
  1429 + var auto_orient = op['auto-orient'] || '',
  1430 + thumbnail = op.thumbnail || '',
  1431 + strip = op.strip || '',
  1432 + gravity = op.gravity || '',
  1433 + crop = op.crop || '',
  1434 + quality = op.quality || '',
  1435 + rotate = op.rotate || '',
  1436 + format = op.format || '',
  1437 + blur = op.blur || '';
  1438 + //Todo check option
  1439 +
  1440 + var imageUrl = 'imageMogr2';
  1441 +
  1442 + imageUrl += auto_orient ? '/auto-orient' : '';
  1443 + imageUrl += thumbnail ? '/thumbnail/' + thumbnail : '';
  1444 + imageUrl += strip ? '/strip' : '';
  1445 + imageUrl += gravity ? '/gravity/' + gravity : '';
  1446 + imageUrl += quality ? '/quality/' + quality : '';
  1447 + imageUrl += crop ? '/crop/' + crop : '';
  1448 + imageUrl += rotate ? '/rotate/' + rotate : '';
  1449 + imageUrl += format ? '/format/' + format : '';
  1450 + imageUrl += blur ? '/blur/' + blur : '';
  1451 +
  1452 + if (key) {
  1453 + imageUrl = this.getUrl(key) + '?' + imageUrl;
  1454 + }
  1455 + return imageUrl;
  1456 + };
  1457 +
  1458 + /**
  1459 + * invoke the watermark api of Qiniu
  1460 + * @param {Object} api params
  1461 + * @param {String} key of file
  1462 + * @return {String} url of processed image
  1463 + */
  1464 + this.watermark = function(op, key) {
  1465 + var mode = op.mode;
  1466 + if (!mode) {
  1467 + return false;
  1468 + }
  1469 +
  1470 + var imageUrl = 'watermark/' + mode;
  1471 +
  1472 + if (mode === 1) {
  1473 + var image = op.image || '';
  1474 + if (!image) {
  1475 + return false;
  1476 + }
  1477 + imageUrl += image ? '/image/' + this.URLSafeBase64Encode(image) : '';
  1478 + } else if (mode === 2) {
  1479 + var text = op.text ? op.text : '',
  1480 + font = op.font ? op.font : '',
  1481 + fontsize = op.fontsize ? op.fontsize : '',
  1482 + fill = op.fill ? op.fill : '';
  1483 + if (!text) {
  1484 + return false;
  1485 + }
  1486 + imageUrl += text ? '/text/' + this.URLSafeBase64Encode(text) : '';
  1487 + imageUrl += font ? '/font/' + this.URLSafeBase64Encode(font) : '';
  1488 + imageUrl += fontsize ? '/fontsize/' + fontsize : '';
  1489 + imageUrl += fill ? '/fill/' + this.URLSafeBase64Encode(fill) : '';
  1490 + } else {
  1491 + // Todo mode3
  1492 + return false;
  1493 + }
  1494 +
  1495 + var dissolve = op.dissolve || '',
  1496 + gravity = op.gravity || '',
  1497 + dx = op.dx || '',
  1498 + dy = op.dy || '';
  1499 +
  1500 + imageUrl += dissolve ? '/dissolve/' + dissolve : '';
  1501 + imageUrl += gravity ? '/gravity/' + gravity : '';
  1502 + imageUrl += dx ? '/dx/' + dx : '';
  1503 + imageUrl += dy ? '/dy/' + dy : '';
  1504 +
  1505 + if (key) {
  1506 + imageUrl = this.getUrl(key) + '?' + imageUrl;
  1507 + }
  1508 + return imageUrl;
  1509 + };
  1510 +
  1511 + /**
  1512 + * invoke the imageInfo api of Qiniu
  1513 + * @param {String} key of file
  1514 + * @return {Object} image info
  1515 + */
  1516 + this.imageInfo = function(key) {
  1517 + if (!key) {
  1518 + return false;
  1519 + }
  1520 + var url = this.getUrl(key) + '?imageInfo';
  1521 + var xhr = this.createAjax();
  1522 + var info;
  1523 + var that = this;
  1524 + xhr.open('GET', url, false);
  1525 + xhr.onreadystatechange = function() {
  1526 + if (xhr.readyState === 4 && xhr.status === 200) {
  1527 + info = that.parseJSON(xhr.responseText);
  1528 + }
  1529 + };
  1530 + xhr.send();
  1531 + return info;
  1532 + };
  1533 +
  1534 + /**
  1535 + * invoke the exif api of Qiniu
  1536 + * @param {String} key of file
  1537 + * @return {Object} image exif
  1538 + */
  1539 + this.exif = function(key) {
  1540 + if (!key) {
  1541 + return false;
  1542 + }
  1543 + var url = this.getUrl(key) + '?exif';
  1544 + var xhr = this.createAjax();
  1545 + var info;
  1546 + var that = this;
  1547 + xhr.open('GET', url, false);
  1548 + xhr.onreadystatechange = function() {
  1549 + if (xhr.readyState === 4 && xhr.status === 200) {
  1550 + info = that.parseJSON(xhr.responseText);
  1551 + }
  1552 + };
  1553 + xhr.send();
  1554 + return info;
  1555 + };
  1556 +
  1557 + /**
  1558 + * invoke the exif or imageInfo api of Qiniu
  1559 + * according with type param
  1560 + * @param {String} ['exif'|'imageInfo']type of info
  1561 + * @param {String} key of file
  1562 + * @return {Object} image exif or info
  1563 + */
  1564 + this.get = function(type, key) {
  1565 + if (!key || !type) {
  1566 + return false;
  1567 + }
  1568 + if (type === 'exif') {
  1569 + return this.exif(key);
  1570 + } else if (type === 'imageInfo') {
  1571 + return this.imageInfo(key);
  1572 + }
  1573 + return false;
  1574 + };
  1575 +
  1576 + /**
  1577 + * invoke api of Qiniu like a pipeline
  1578 + * @param {Array of Object} params of a series api call
  1579 + * each object in array is options of api which name is set as 'fop' property
  1580 + * each api's output will be next api's input
  1581 + * @param {String} key of file
  1582 + * @return {String|Boolean} url of processed image
  1583 + */
  1584 + this.pipeline = function(arr, key) {
  1585 + var isArray = Object.prototype.toString.call(arr) === '[object Array]';
  1586 + var option, errOp, imageUrl = '';
  1587 + if (isArray) {
  1588 + for (var i = 0, len = arr.length; i < len; i++) {
  1589 + option = arr[i];
  1590 + if (!option.fop) {
  1591 + return false;
  1592 + }
  1593 + switch (option.fop) {
  1594 + case 'watermark':
  1595 + imageUrl += this.watermark(option) + '|';
  1596 + break;
  1597 + case 'imageView2':
  1598 + imageUrl += this.imageView2(option) + '|';
  1599 + break;
  1600 + case 'imageMogr2':
  1601 + imageUrl += this.imageMogr2(option) + '|';
  1602 + break;
  1603 + default:
  1604 + errOp = true;
  1605 + break;
  1606 + }
  1607 + if (errOp) {
  1608 + return false;
  1609 + }
  1610 + }
  1611 + if (key) {
  1612 + imageUrl = this.getUrl(key) + '?' + imageUrl;
  1613 + var length = imageUrl.length;
  1614 + if (imageUrl.slice(length - 1) === '|') {
  1615 + imageUrl = imageUrl.slice(0, length - 1);
  1616 + }
  1617 + }
  1618 + return imageUrl;
  1619 + }
  1620 + return false;
  1621 + };
  1622 +}
  1623 +
  1624 +var Qiniu = new QiniuJsSDK();
  1625 +
  1626 +global.Qiniu = Qiniu;
  1627 +
  1628 +global.QiniuJsSDK = QiniuJsSDK;
  1629 +
  1630 +})( window );
parent/center.manager/src/main/webapp/WEB-INF/static/js/plugins/qiniu/qiniu.min.js View file @ a2758e4
  1 +/*! qiniu-js v1.0.19 | Copyright 2015 by Qiniu */
  2 +!function(global){function createCookie(a,b,c){var d=new Date;d.setTime(d.getTime()+24*c*60*60*1e3);var e="; expires="+d.toGMTString();document.cookie=a+"="+b+e+"; path=/"}function readCookie(a){var b=a+"=";var c=document.cookie.split(";");for(var d=0,e=c.length;e>d;d++){var f=c[d];while(" "===f.charAt(0))f=f.substring(1,f.length);if(0===f.indexOf(b))return f.substring(b.length,f.length)}return null}window.localStorage||(window.localStorage={setItem:function(a,b){createCookie(a,b,30)},getItem:function(a){return readCookie(a)},removeItem:function(a){createCookie(a,"",-1)}});function QiniuJsSDK(){var that=this;this.detectIEVersion=function(){var a=4,b=document.createElement("div"),c=b.getElementsByTagName("i");while(b.innerHTML="<!--[if gt IE "+a+"]><i></i><![endif]-->",c[0])a++;return a>4?a:!1};var logger={MUTE:0,FATA:1,ERROR:2,WARN:3,INFO:4,DEBUG:5,TRACE:6,level:0};function log(a,b){var c="[qiniu-js-sdk]["+a+"]";var d=c;for(var e=0;e<b.length;e++)d+="string"==typeof b[e]?" "+b[e]:" "+that.stringifyJSON(b[e]);that.detectIEVersion()?console.log(d):(b.unshift(c),console.log.apply(console,b)),document.getElementById("qiniu-js-sdk-log")&&(document.getElementById("qiniu-js-sdk-log").innerHTML+="<p>"+d+"</p>")}function makeLogFunc(a){var b=a.toLowerCase();logger[b]=function(){if(window.console&&window.console.log&&logger.level>=logger[a]){var c=Array.prototype.slice.call(arguments);log(b,c)}}}for(var property in logger)logger.hasOwnProperty(property)&&"number"==typeof logger[property]&&!logger.hasOwnProperty(property.toLowerCase())&&makeLogFunc(property);var qiniuUploadUrl;qiniuUploadUrl="https:"===window.location.protocol?"https://up.qbox.me":"http://upload.qiniu.com";var qiniuUploadUrls=["http://upload.qiniu.com","http://up.qiniu.com"];var qiniuUpHosts={http:["http://upload.qiniu.com","http://up.qiniu.com"],https:["https://up.qbox.me"]};var changeUrlTimes=0;this.resetUploadUrl=function(){var a="https:"===window.location.protocol?qiniuUpHosts.https:qiniuUpHosts.http;var b=changeUrlTimes%a.length;qiniuUploadUrl=a[b],changeUrlTimes++,logger.debug("resetUploadUrl: "+qiniuUploadUrl)},this.isImage=function(a){return a=a.split(/[?#]/)[0],/\.(png|jpg|jpeg|gif|bmp)$/i.test(a)},this.getFileExtension=function(a){var b=a.split(".");var c;return c=1===b.length||""===b[0]&&2===b.length?"":b.pop().toLowerCase()},this.utf8_encode=function(a){if(null===a||"undefined"==typeof a)return"";var b=a+"";var c="",d,e,f=0;d=e=0,f=b.length;for(var g=0;f>g;g++){var h=b.charCodeAt(g);var i=null;if(128>h)e++;else if(h>127&&2048>h)i=String.fromCharCode(h>>6|192,63&h|128);else if(63488&h^!0)i=String.fromCharCode(h>>12|224,h>>6&63|128,63&h|128);else{if(64512&h^!0)throw new RangeError("Unmatched trail surrogate at "+g);var j=b.charCodeAt(++g);if(64512&j^!0)throw new RangeError("Unmatched lead surrogate at "+(g-1));h=((1023&h)<<10)+(1023&j)+65536,i=String.fromCharCode(h>>18|240,h>>12&63|128,h>>6&63|128,63&h|128)}null!==i&&(e>d&&(c+=b.slice(d,e)),c+=i,d=e=g+1)}return e>d&&(c+=b.slice(d,f)),c},this.base64_decode=function(a){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var c,d,e,f,g,h,i,j,k=0,l=0,m="",n=[];if(!a)return a;a+="";do f=b.indexOf(a.charAt(k++)),g=b.indexOf(a.charAt(k++)),h=b.indexOf(a.charAt(k++)),i=b.indexOf(a.charAt(k++)),j=f<<18|g<<12|h<<6|i,c=j>>16&255,d=j>>8&255,e=255&j,64===h?n[l++]=String.fromCharCode(c):64===i?n[l++]=String.fromCharCode(c,d):n[l++]=String.fromCharCode(c,d,e);while(k<a.length);return m=n.join("")},this.base64_encode=function(a){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var c,d,e,f,g,h,i,j,k=0,l=0,m="",n=[];if(!a)return a;a=this.utf8_encode(a+"");do c=a.charCodeAt(k++),d=a.charCodeAt(k++),e=a.charCodeAt(k++),j=c<<16|d<<8|e,f=j>>18&63,g=j>>12&63,h=j>>6&63,i=63&j,n[l++]=b.charAt(f)+b.charAt(g)+b.charAt(h)+b.charAt(i);while(k<a.length);switch(m=n.join(""),a.length%3){case 1:m=m.slice(0,-2)+"==";break;case 2:m=m.slice(0,-1)+"="}return m},this.URLSafeBase64Encode=function(a){return a=this.base64_encode(a),a.replace(/\//g,"_").replace(/\+/g,"-")},this.URLSafeBase64Decode=function(a){return a=a.replace(/_/g,"/").replace(/-/g,"+"),this.base64_decode(a)},this.createAjax=function(a){var b={};return b=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP")},this.parseJSON=function(data){if(window.JSON&&window.JSON.parse)return window.JSON.parse(data);var rx_dangerous=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;var text=String(data);return rx_dangerous.lastIndex=0,rx_dangerous.test(text)&&(text=text.replace(rx_dangerous,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})),eval("("+text+")")},this.stringifyJSON=function(a){if(window.JSON&&window.JSON.stringify)return window.JSON.stringify(a);switch(typeof a){case"string":return'"'+a.replace(/(["\\])/g,"\\$1")+'"';case"array":return"["+a.map(that.stringifyJSON).join(",")+"]";case"object":if(a instanceof Array){var b=[];var c=a.length;for(var d=0;c>d;d++)b.push(that.stringifyJSON(a[d]));return"["+b.join(",")+"]"}if(null===a)return"null";var e=[];for(var f in a)a.hasOwnProperty(f)&&e.push(that.stringifyJSON(f)+":"+that.stringifyJSON(a[f]));return"{"+e.join(",")+"}";case"number":return a;case!1:return a;case"boolean":return a}},this.trim=function(a){return null===a?"":a.replace(/^\s+|\s+$/g,"")},this.uploader=function(a){var b=function(){var b=that.detectIEVersion();var c,d,e;var f="Safari"===mOxie.Env.browser&&mOxie.Env.version<=5&&"Windows"===mOxie.Env.os&&"7"===mOxie.Env.osVersion||"Safari"===mOxie.Env.browser&&"iOS"===mOxie.Env.os&&"7"===mOxie.Env.osVersion;b&&9>b&&a.chunk_size&&a.runtimes.indexOf("flash")>=0?a.chunk_size=0:f?a.chunk_size=0:(c=20,d=4<<c,e=plupload.parseSize(a.chunk_size),e>d&&(a.chunk_size=d))};var c=function(a){var b=[];for(var c=0;c<a.length;c++){var d=a[c];0===d.indexOf("-H")?b.push(d.split(" ")[2]):b.push(d)}return b};var d=function(a){var b=a.split(":");var c=b[0];var d=that.parseJSON(that.URLSafeBase64Decode(b[2]));return d.ak=c,d.scope.indexOf(":")>=0?(d.bucket=d.scope.split(":")[0],d.key=d.scope.split(":")[1]):d.bucket=d.scope,d};var e=function(b){var e=d(b);var f=window.location.protocol+"//uc.qbox.me/v1/query?ak="+e.ak+"&bucket="+e.bucket;logger.debug("putPolicy: ",e),logger.debug("get uphosts from: ",f);var g=that.detectIEVersion();var h;g&&9>=g?(h=new mOxie.XMLHttpRequest,mOxie.Env.swf_url=a.flash_swf_url):h=that.createAjax(),h.open("GET",f,!1);var i=function(){if(logger.debug("ajax.readyState: ",h.readyState),4===h.readyState)if(logger.debug("ajax.status: ",h.status),h.status<400){var a=that.parseJSON(h.responseText);qiniuUpHosts.http=c(a.http.up),qiniuUpHosts.https=c(a.https.up),logger.debug("get new uphosts: ",qiniuUpHosts),that.resetUploadUrl()}else logger.error("get uphosts error: ",h.responseText)};g&&9>=g?h.bind("readystatechange",i):h.onreadystatechange=i,h.send()};var f=function(b){return!that.token||a.uptoken_url&&that.tokenInfo.isExpired()?g(b):that.token};var g=function(b){if(a.uptoken)that.token=a.uptoken;else if(a.uptoken_url){logger.debug("get uptoken from: ",that.uptoken_url);var c=that.createAjax();if(c.open("GET",that.uptoken_url,!1),c.setRequestHeader("If-Modified-Since","0"),c.send(),200===c.status){var d=that.parseJSON(c.responseText);that.token=d.uptoken;var f=that.token.split(":");var g=that.parseJSON(that.URLSafeBase64Decode(f[2]));that.tokenMap||(that.tokenMap={});var h=function(a){return Math.ceil(a.getTime()/1e3)};var i=h(new Date(c.getResponseHeader("date")));var j=h(new Date);that.tokenInfo={serverDelay:j-i,deadline:g.deadline,isExpired:function(){var a=this.deadline-h(new Date)+this.serverDelay;return 600>a}},logger.debug("get new uptoken: ",that.token),logger.debug("get token info: ",that.tokenInfo)}else logger.error("get uptoken error: ",c.responseText)}else a.uptoken_func?(logger.debug("get uptoken from uptoken_func"),that.token=a.uptoken_func(b),logger.debug("get new uptoken: ",that.token)):logger.error("one of [uptoken, uptoken_url, uptoken_func] settings in options is required!");return that.token&&e(that.token),that.token};var h=function(b,c,d){var e="",f=!1;if(!a.save_key)if(f=b.getOption&&b.getOption("unique_names"),f=f||b.settings&&b.settings.unique_names){var g=that.getFileExtension(c.name);e=g?c.id+"."+g:c.id}else e="function"==typeof d?d(b,c):c.name;return e};if(a.log_level&&(logger.level=a.log_level),!a.domain)throw"domain setting in options is required!";if(!a.browse_button)throw"browse_button setting in options is required!";if(!a.uptoken&&!a.uptoken_url&&!a.uptoken_func)throw"one of [uptoken, uptoken_url, uptoken_func] settings in options is required!";logger.debug("init uploader start"),logger.debug("environment: ",mOxie.Env),logger.debug("userAgent: ",navigator.userAgent);var i={};var j=a.init&&a.init.Error;var k=a.init&&a.init.FileUploaded;a.init.Error=function(){},a.init.FileUploaded=function(){},that.uptoken_url=a.uptoken_url,that.token="",that.key_handler="function"==typeof a.init.Key?a.init.Key:"",this.domain=a.domain;var l="";var m={isResumeUpload:!1,resumeFilesize:0,startTime:"",currentTime:""};b(),logger.debug("invoke reset_chunk_size()"),logger.debug("op.chunk_size: ",a.chunk_size);var n={url:qiniuUploadUrl,multipart_params:{token:""}};var o=that.detectIEVersion();o&&9>=o&&(n.multipart_params.accept="text/plain; charset=utf-8",logger.debug("add accept text/plain in multipart params")),plupload.extend(i,a,n),logger.debug("option: ",i);var p=new plupload.Uploader(i);logger.debug("new plupload.Uploader(option)"),p.bind("Init",function(b,c){logger.debug("Init event activated"),a.get_new_uptoken||g(null)}),logger.debug("bind Init event"),p.bind("FilesAdded",function(a,b){logger.debug("FilesAdded event activated");var c=a.getOption&&a.getOption("auto_start");c=c||a.settings&&a.settings.auto_start,logger.debug("auto_start: ",c),logger.debug("files: ",b);var d=function(){return"ios"===mOxie.Env.OS.toLowerCase()?!0:!1};if(d())for(var e=0;e<b.length;e++){var f=b[e];var g=that.getFileExtension(f.name);f.name=f.id+"."+g}c&&setTimeout(function(){a.start(),logger.debug("invoke up.start()")},0),a.refresh()}),logger.debug("bind FilesAdded event"),p.bind("BeforeUpload",function(b,c){logger.debug("BeforeUpload event activated"),c.speed=c.speed||0,l="",a.get_new_uptoken&&g(c);var d=function(b,c,d){m.startTime=(new Date).getTime();var f;f=a.save_key?{token:that.token}:{key:h(b,c,d),token:that.token};var g=that.detectIEVersion();g&&9>=g&&(f.accept="text/plain; charset=utf-8",logger.debug("add accept text/plain in multipart params")),logger.debug("directUpload multipart_params_obj: ",f);var i=a.x_vars;if(void 0!==i&&"object"==typeof i)for(var j in i)i.hasOwnProperty(j)&&("function"==typeof i[j]?f["x:"+j]=i[j](b,c):"object"!=typeof i[j]&&(f["x:"+j]=i[j]));b.setOption({url:qiniuUploadUrl,multipart:!0,chunk_size:e()?a.max_file_size:void 0,multipart_params:f})};var e=function(){var a=navigator.userAgent.toLowerCase();return(a.match(/MicroMessenger/i)||"QQBrowser"===mOxie.Env.browser||a.match(/V1_AND_SQ/i))&&"android"===mOxie.Env.OS.toLowerCase()?!0:!1};var i=b.getOption&&b.getOption("chunk_size");if(i=i||b.settings&&b.settings.chunk_size,logger.debug("uploader.runtime: ",p.runtime),logger.debug("chunk_size: ",i),"html5"!==p.runtime&&"flash"!==p.runtime||!i)logger.debug("directUpload because uploader.runtime !== 'html5' || uploader.runtime !== 'flash' || !chunk_size"),d(b,c,that.key_handler);else if(c.size<i||e())logger.debug("directUpload because file.size < chunk_size || is_android_weixin_or_qq()"),d(b,c,that.key_handler);else{var j=localStorage.getItem(c.name);var k=i;if(j){j=that.parseJSON(j);var n=(new Date).getTime();var o=j.time||0;var q=864e5;q>n-o&&100!==j.percent&&c.size===j.total?(c.percent=j.percent,c.loaded=j.offset,l=j.ctx,m.isResumeUpload=!0,m.resumeFilesize=j.offset,j.offset+k>c.size&&(k=c.size-j.offset)):localStorage.removeItem(c.name)}m.startTime=(new Date).getTime();var r={};var s=that.detectIEVersion();s&&9>=s&&(r.accept="text/plain; charset=utf-8",logger.debug("add accept text/plain in multipart params")),b.setOption({url:qiniuUploadUrl+"/mkblk/"+k,multipart:!1,chunk_size:i,required_features:"chunks",headers:{Authorization:"UpToken "+f(c)},multipart_params:r})}}),logger.debug("bind BeforeUpload event"),p.bind("UploadProgress",function(a,b){logger.trace("UploadProgress event activated"),m.currentTime=(new Date).getTime();var c=m.currentTime-m.startTime;var d=b.loaded||0;m.isResumeUpload&&(d=b.loaded-m.resumeFilesize),b.speed=(d/c*1e3).toFixed(0)||0}),logger.debug("bind UploadProgress event"),p.bind("ChunkUploaded",function(a,b,c){logger.debug("ChunkUploaded event activated"),logger.debug("file: ",b),logger.debug("info: ",c);var d=that.parseJSON(c.response);logger.debug("res: ",d),l=l?l+","+d.ctx:d.ctx;var e=c.total-c.offset;var g=a.getOption&&a.getOption("chunk_size");g=g||a.settings&&a.settings.chunk_size,g>e&&(a.setOption({url:qiniuUploadUrl+"/mkblk/"+e}),logger.debug("up.setOption url: ",qiniuUploadUrl+"/mkblk/"+e)),a.setOption({headers:{Authorization:"UpToken "+f(b)}}),localStorage.setItem(b.name,that.stringifyJSON({ctx:l,percent:b.percent,total:c.total,offset:c.offset,time:(new Date).getTime()}))}),logger.debug("bind ChunkUploaded event");var q=qiniuUploadUrls.length;var r=function(a){return q-->0?(setTimeout(function(){that.resetUploadUrl(),a.status=plupload.QUEUED,p.stop(),p.start()},0),!0):(q=qiniuUploadUrls.length,!1)};return p.bind("Error",function(a){return function(b,c){logger.error("Error event activated"),logger.error("err: ",c);var d="";var e=c.file;if(e){switch(c.code){case plupload.FAILED:d="\u4e0a\u4f20\u5931\u8d25\u3002\u8bf7\u7a0d\u540e\u518d\u8bd5\u3002";break;case plupload.FILE_SIZE_ERROR:var f=b.getOption&&b.getOption("max_file_size");f=f||b.settings&&b.settings.max_file_size,d="\u6d4f\u89c8\u5668\u6700\u5927\u53ef\u4e0a\u4f20"+f+"\u3002\u66f4\u5927\u6587\u4ef6\u8bf7\u4f7f\u7528\u547d\u4ee4\u884c\u5de5\u5177\u3002";break;case plupload.FILE_EXTENSION_ERROR:d="\u6587\u4ef6\u9a8c\u8bc1\u5931\u8d25\u3002\u8bf7\u7a0d\u540e\u91cd\u8bd5\u3002";break;case plupload.HTTP_ERROR:if(""===c.response){if(d=c.message||"\u672a\u77e5\u7f51\u7edc\u9519\u8bef\u3002",!r(e))return;break}var g=that.parseJSON(c.response);var h=g.error;switch(c.status){case 400:d="\u8bf7\u6c42\u62a5\u6587\u683c\u5f0f\u9519\u8bef\u3002";break;case 401:d="\u5ba2\u6237\u7aef\u8ba4\u8bc1\u6388\u6743\u5931\u8d25\u3002\u8bf7\u91cd\u8bd5\u6216\u63d0\u4ea4\u53cd\u9988\u3002";break;case 405:d="\u5ba2\u6237\u7aef\u8bf7\u6c42\u9519\u8bef\u3002\u8bf7\u91cd\u8bd5\u6216\u63d0\u4ea4\u53cd\u9988\u3002";break;case 579:d="\u8d44\u6e90\u4e0a\u4f20\u6210\u529f\uff0c\u4f46\u56de\u8c03\u5931\u8d25\u3002";break;case 599:if(d="\u7f51\u7edc\u8fde\u63a5\u5f02\u5e38\u3002\u8bf7\u91cd\u8bd5\u6216\u63d0\u4ea4\u53cd\u9988\u3002",!r(e))return;break;case 614:d="\u6587\u4ef6\u5df2\u5b58\u5728\u3002";try{g=that.parseJSON(g.error),h=g.error||"file exists"}catch(i){h=g.error||"file exists"}break;case 631:d="\u6307\u5b9a\u7a7a\u95f4\u4e0d\u5b58\u5728\u3002";break;case 701:d="\u4e0a\u4f20\u6570\u636e\u5757\u6821\u9a8c\u51fa\u9519\u3002\u8bf7\u91cd\u8bd5\u6216\u63d0\u4ea4\u53cd\u9988\u3002";break;default:if(d="\u672a\u77e5\u9519\u8bef\u3002",!r(e))return}d=d+"("+c.status+"\uff1a"+h+")";break;case plupload.SECURITY_ERROR:d="\u5b89\u5168\u914d\u7f6e\u9519\u8bef\u3002\u8bf7\u8054\u7cfb\u7f51\u7ad9\u7ba1\u7406\u5458\u3002";break;case plupload.GENERIC_ERROR:d="\u4e0a\u4f20\u5931\u8d25\u3002\u8bf7\u7a0d\u540e\u518d\u8bd5\u3002";break;case plupload.IO_ERROR:d="\u4e0a\u4f20\u5931\u8d25\u3002\u8bf7\u7a0d\u540e\u518d\u8bd5\u3002";break;case plupload.INIT_ERROR:d="\u7f51\u7ad9\u914d\u7f6e\u9519\u8bef\u3002\u8bf7\u8054\u7cfb\u7f51\u7ad9\u7ba1\u7406\u5458\u3002",p.destroy();break;default:if(d=c.message+c.details,!r(e))return}a&&a(b,c,d)}b.refresh()}}(j)),logger.debug("bind Error event"),p.bind("FileUploaded",function(b){return function(c,d,e){logger.debug("FileUploaded event activated"),logger.debug("file: ",d),logger.debug("info: ",e);var f=function(c,d,e){if(a.downtoken_url){var f=that.createAjax();f.open("POST",a.downtoken_url,!0),f.setRequestHeader("Content-type","application/x-www-form-urlencoded"),f.onreadystatechange=function(){if(4===f.readyState)if(200===f.status){var a;try{a=that.parseJSON(f.responseText)}catch(g){throw"invalid json format"}var h={};plupload.extend(h,that.parseJSON(e),a),b&&b(c,d,that.stringifyJSON(h))}else p.trigger("Error",{status:f.status,response:f.responseText,file:d,code:plupload.HTTP_ERROR})},f.send("key="+that.parseJSON(e).key+"&domain="+a.domain)}else b&&b(c,d,e)};var g=that.parseJSON(e.response);if(l=l?l:g.ctx,logger.debug("ctx: ",l),l){var i="";logger.debug("save_key: ",a.save_key),a.save_key||(i=h(c,d,that.key_handler),i=i?"/key/"+that.URLSafeBase64Encode(i):"");var j="/fname/"+that.URLSafeBase64Encode(d.name);logger.debug("op.x_vars: ",a.x_vars);var k=a.x_vars,m="",n="";if(void 0!==k&&"object"==typeof k)for(var o in k)k.hasOwnProperty(o)&&("function"==typeof k[o]?m=that.URLSafeBase64Encode(k[o](c,d)):"object"!=typeof k[o]&&(m=that.URLSafeBase64Encode(k[o])),n+="/x:"+o+"/"+m);var q=qiniuUploadUrl+"/mkfile/"+d.size+i+j+n;var r=that.detectIEVersion();var s;r&&9>=r?(s=new mOxie.XMLHttpRequest,mOxie.Env.swf_url=a.flash_swf_url):s=that.createAjax(),s.open("POST",q,!0),s.setRequestHeader("Content-Type","text/plain;charset=UTF-8"),s.setRequestHeader("Authorization","UpToken "+that.token);var t=function(){if(logger.debug("ajax.readyState: ",s.readyState),4===s.readyState){localStorage.removeItem(d.name);var a;200===s.status?(a=s.responseText,logger.debug("mkfile is success: ",a),f(c,d,a)):(a={status:s.status,response:s.responseText,file:d,code:-200,responseHeaders:s.getAllResponseHeaders()},logger.debug("mkfile is error: ",a),p.trigger("Error",a))}};r&&9>=r?s.bind("readystatechange",t):s.onreadystatechange=t,s.send(l),logger.debug("mkfile: ",q)}else f(c,d,e.response)}}(k)),logger.debug("bind FileUploaded event"),p.init(),logger.debug("invoke uploader.init()"),logger.debug("init uploader end"),p},this.getUrl=function(a){if(!a)return!1;a=encodeURI(a);var b=this.domain;return"/"!==b.slice(b.length-1)&&(b+="/"),b+a},this.imageView2=function(a,b){if(!/^\d$/.test(a.mode))return!1;var c=a.mode,d=a.w||"",e=a.h||"",f=a.q||"",g=a.format||"";if(!d&&!e)return!1;var h="imageView2/"+c;return h+=d?"/w/"+d:"",h+=e?"/h/"+e:"",h+=f?"/q/"+f:"",h+=g?"/format/"+g:"",b&&(h=this.getUrl(b)+"?"+h),h},this.imageMogr2=function(a,b){var c=a["auto-orient"]||"",d=a.thumbnail||"",e=a.strip||"",f=a.gravity||"",g=a.crop||"",h=a.quality||"",i=a.rotate||"",j=a.format||"",k=a.blur||"";var l="imageMogr2";return l+=c?"/auto-orient":"",l+=d?"/thumbnail/"+d:"",l+=e?"/strip":"",l+=f?"/gravity/"+f:"",l+=h?"/quality/"+h:"",l+=g?"/crop/"+g:"",l+=i?"/rotate/"+i:"",l+=j?"/format/"+j:"",l+=k?"/blur/"+k:"",b&&(l=this.getUrl(b)+"?"+l),l},this.watermark=function(a,b){var c=a.mode;if(!c)return!1;var d="watermark/"+c;if(1===c){var e=a.image||"";if(!e)return!1;d+=e?"/image/"+this.URLSafeBase64Encode(e):""}else{if(2!==c)return!1;var f=a.text?a.text:"",g=a.font?a.font:"",h=a.fontsize?a.fontsize:"",i=a.fill?a.fill:"";if(!f)return!1;d+=f?"/text/"+this.URLSafeBase64Encode(f):"",d+=g?"/font/"+this.URLSafeBase64Encode(g):"",d+=h?"/fontsize/"+h:"",d+=i?"/fill/"+this.URLSafeBase64Encode(i):""}var j=a.dissolve||"",k=a.gravity||"",l=a.dx||"",m=a.dy||"";return d+=j?"/dissolve/"+j:"",d+=k?"/gravity/"+k:"",d+=l?"/dx/"+l:"",d+=m?"/dy/"+m:"",b&&(d=this.getUrl(b)+"?"+d),d},this.imageInfo=function(a){if(!a)return!1;var b=this.getUrl(a)+"?imageInfo";var c=this.createAjax();var d;var e=this;return c.open("GET",b,!1),c.onreadystatechange=function(){4===c.readyState&&200===c.status&&(d=e.parseJSON(c.responseText))},c.send(),d},this.exif=function(a){if(!a)return!1;var b=this.getUrl(a)+"?exif";var c=this.createAjax();var d;var e=this;return c.open("GET",b,!1),c.onreadystatechange=function(){4===c.readyState&&200===c.status&&(d=e.parseJSON(c.responseText))},c.send(),d},this.get=function(a,b){return b&&a?"exif"===a?this.exif(b):"imageInfo"===a?this.imageInfo(b):!1:!1},this.pipeline=function(a,b){var c="[object Array]"===Object.prototype.toString.call(a);var d,e,f="";if(c){for(var g=0,h=a.length;h>g;g++){if(d=a[g],!d.fop)return!1;switch(d.fop){case"watermark":f+=this.watermark(d)+"|";break;case"imageView2":f+=this.imageView2(d)+"|";break;case"imageMogr2":f+=this.imageMogr2(d)+"|";break;default:e=!0}if(e)return!1}if(b){f=this.getUrl(b)+"?"+f;var i=f.length;"|"===f.slice(i-1)&&(f=f.slice(0,i-1))}return f}return!1}}var Qiniu=new QiniuJsSDK;global.Qiniu=Qiniu,global.QiniuJsSDK=QiniuJsSDK}(window);
  3 +//# sourceMappingURL=dist/qiniu.min.map
parent/center.manager/src/main/webapp/WEB-INF/static/js/plugins/qiniu/ui.js View file @ a2758e4
  1 +/*global plupload */
  2 +/*global qiniu */
  3 +function FileProgress(file, targetID) {
  4 + this.fileProgressID = file.id;
  5 + this.file = file;
  6 +
  7 + this.opacity = 100;
  8 + this.height = 0;
  9 + this.fileProgressWrapper = $('#' + this.fileProgressID);
  10 + if (!this.fileProgressWrapper.length) {
  11 + // <div class="progress">
  12 + // <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%">
  13 + // <span class="sr-only">20% Complete</span>
  14 + // </div>
  15 + // </div>
  16 +
  17 + this.fileProgressWrapper = $('<tr></tr>');
  18 + var Wrappeer = this.fileProgressWrapper;
  19 + Wrappeer.attr('id', this.fileProgressID).addClass('progressContainer');
  20 +
  21 + var progressText = $("<td/>");
  22 + progressText.addClass('progressName').text(file.name);
  23 +
  24 +
  25 + var fileSize = plupload.formatSize(file.size).toUpperCase();
  26 + var progressSize = $("<td/>");
  27 + progressSize.addClass("progressFileSize").text(fileSize);
  28 +
  29 + var progressBarTd = $("<td/>");
  30 + var progressBarBox = $("<div/>");
  31 + progressBarBox.addClass('info');
  32 + var progressBarWrapper = $("<div/>");
  33 + progressBarWrapper.addClass("progress progress-striped");
  34 +
  35 + var progressBar = $("<div/>");
  36 + progressBar.addClass("progress-bar progress-bar-info")
  37 + .attr('role', 'progressbar')
  38 + .attr('aria-valuemax', 100)
  39 + .attr('aria-valuenow', 0)
  40 + .attr('aria-valuein', 0)
  41 + .width('0%');
  42 +
  43 + var progressBarPercent = $('<span class=sr-only />');
  44 + progressBarPercent.text(fileSize);
  45 +
  46 + var progressCancel = $('<a href=javascript:; />');
  47 + progressCancel.show().addClass('progressCancel').text('×');
  48 +
  49 + progressBar.append(progressBarPercent);
  50 + progressBarWrapper.append(progressBar);
  51 + progressBarBox.append(progressBarWrapper);
  52 + progressBarBox.append(progressCancel);
  53 +
  54 + var progressBarStatus = $('<div class="status text-center"/>');
  55 + progressBarBox.append(progressBarStatus);
  56 + progressBarTd.append(progressBarBox);
  57 +
  58 + Wrappeer.append(progressText);
  59 + Wrappeer.append(progressSize);
  60 + Wrappeer.append(progressBarTd);
  61 +
  62 + $('#' + targetID).append(Wrappeer);
  63 + } else {
  64 + this.reset();
  65 + }
  66 +
  67 + this.height = this.fileProgressWrapper.offset().top;
  68 + this.setTimer(null);
  69 +}
  70 +
  71 +FileProgress.prototype.setTimer = function(timer) {
  72 + this.fileProgressWrapper.FP_TIMER = timer;
  73 +};
  74 +
  75 +FileProgress.prototype.getTimer = function(timer) {
  76 + return this.fileProgressWrapper.FP_TIMER || null;
  77 +};
  78 +
  79 +FileProgress.prototype.reset = function() {
  80 + this.fileProgressWrapper.attr('class', "progressContainer");
  81 + this.fileProgressWrapper.find('td .progress .progress-bar-info').attr('aria-valuenow', 0).width('0%').find('span').text('');
  82 + this.appear();
  83 +};
  84 +
  85 +FileProgress.prototype.setChunkProgess = function(chunk_size) {
  86 + var chunk_amount = Math.ceil(this.file.size / chunk_size);
  87 + if (chunk_amount === 1) {
  88 + return false;
  89 + }
  90 +
  91 + var viewProgess = $('<button class="btn btn-default">查看分块上传进度</button>');
  92 +
  93 + var progressBarChunkTr = $('<tr class="chunk-status-tr"><td colspan=3></td></tr>');
  94 + var progressBarChunk = $('<div/>');
  95 + for (var i = 1; i <= chunk_amount; i++) {
  96 + var col = $('<div class="col-md-2"/>');
  97 + var progressBarWrapper = $('<div class="progress progress-striped"></div');
  98 +
  99 + var progressBar = $("<div/>");
  100 + progressBar.addClass("progress-bar progress-bar-info text-left")
  101 + .attr('role', 'progressbar')
  102 + .attr('aria-valuemax', 100)
  103 + .attr('aria-valuenow', 0)
  104 + .attr('aria-valuein', 0)
  105 + .width('0%')
  106 + .attr('id', this.file.id + '_' + i)
  107 + .text('');
  108 +
  109 + var progressBarStatus = $('<span/>');
  110 + progressBarStatus.addClass('chunk-status').text();
  111 +
  112 + progressBarWrapper.append(progressBar);
  113 + progressBarWrapper.append(progressBarStatus);
  114 +
  115 + col.append(progressBarWrapper);
  116 + progressBarChunk.append(col);
  117 + }
  118 +
  119 + if(!this.fileProgressWrapper.find('td:eq(2) .btn-default').length){
  120 + this.fileProgressWrapper.find('td>div').append(viewProgess);
  121 + }
  122 + progressBarChunkTr.hide().find('td').append(progressBarChunk);
  123 + progressBarChunkTr.insertAfter(this.fileProgressWrapper);
  124 +
  125 +};
  126 +
  127 +FileProgress.prototype.setProgress = function(percentage, speed, chunk_size) {
  128 + this.fileProgressWrapper.attr('class', "progressContainer green");
  129 +
  130 + var file = this.file;
  131 + var uploaded = file.loaded;
  132 +
  133 + var size = plupload.formatSize(uploaded).toUpperCase();
  134 + var formatSpeed = plupload.formatSize(speed).toUpperCase();
  135 + var progressbar = this.fileProgressWrapper.find('td .progress').find('.progress-bar-info');
  136 + if (this.fileProgressWrapper.find('.status').text() === '取消上传'){
  137 + return;
  138 + }
  139 + this.fileProgressWrapper.find('.status').text("已上传: " + size + " 上传速度: " + formatSpeed + "/s");
  140 + percentage = parseInt(percentage, 10);
  141 + if (file.status !== plupload.DONE && percentage === 100) {
  142 + percentage = 99;
  143 + }
  144 +
  145 + progressbar.attr('aria-valuenow', percentage).css('width', percentage + '%');
  146 +
  147 + if (chunk_size) {
  148 + var chunk_amount = Math.ceil(file.size / chunk_size);
  149 + if (chunk_amount === 1) {
  150 + return false;
  151 + }
  152 + var current_uploading_chunk = Math.ceil(uploaded / chunk_size);
  153 + var pre_chunk, text;
  154 +
  155 + for (var index = 0; index < current_uploading_chunk; index++) {
  156 + pre_chunk = $('#' + file.id + "_" + index);
  157 + pre_chunk.width('100%').removeClass().addClass('alert-success').attr('aria-valuenow', 100);
  158 + text = "块" + index + "上传进度100%";
  159 + pre_chunk.next().html(text);
  160 + }
  161 +
  162 + var currentProgessBar = $('#' + file.id + "_" + current_uploading_chunk);
  163 + var current_chunk_percent;
  164 + if (current_uploading_chunk < chunk_amount) {
  165 + if (uploaded % chunk_size) {
  166 + current_chunk_percent = ((uploaded % chunk_size) / chunk_size * 100).toFixed(2);
  167 + } else {
  168 + current_chunk_percent = 100;
  169 + currentProgessBar.removeClass().addClass('alert-success');
  170 + }
  171 + } else {
  172 + var last_chunk_size = file.size - chunk_size * (chunk_amount - 1);
  173 + var left_file_size = file.size - uploaded;
  174 + if (left_file_size % last_chunk_size) {
  175 + current_chunk_percent = ((uploaded % chunk_size) / last_chunk_size * 100).toFixed(2);
  176 + } else {
  177 + current_chunk_percent = 100;
  178 + currentProgessBar.removeClass().addClass('alert-success');
  179 + }
  180 + }
  181 + currentProgessBar.width(current_chunk_percent + '%');
  182 + currentProgessBar.attr('aria-valuenow', current_chunk_percent);
  183 + text = "块" + current_uploading_chunk + "上传进度" + current_chunk_percent + '%';
  184 + currentProgessBar.next().html(text);
  185 + }
  186 +
  187 + this.appear();
  188 +};
  189 +
  190 +FileProgress.prototype.setComplete = function(up, info) {
  191 + var td = this.fileProgressWrapper.find('td:eq(2)'),
  192 + tdProgress = td.find('.progress');
  193 +
  194 + var res = $.parseJSON(info);
  195 + var url;
  196 + if (res.url) {
  197 + url = res.url;
  198 + str = "<div><strong>Link:</strong><a href=" + res.url + " target='_blank' > " + res.url + "</a></div>" +
  199 + "<div class=hash><strong>Hash:</strong>" + res.hash + "</div>";
  200 + } else {
  201 + var domain = up.getOption('domain');
  202 + url = domain + encodeURI(res.key);
  203 + var link = domain + res.key;
  204 + str = "<div><strong>Link:</strong><a href=" + url + " target='_blank' > " + link + "</a></div>" +
  205 + "<div class=hash><strong>Hash:</strong>" + res.hash + "</div>";
  206 + }
  207 +
  208 + tdProgress.html(str).removeClass().next().next('.status').hide();
  209 + td.find('.progressCancel').hide();
  210 +
  211 + var progressNameTd = this.fileProgressWrapper.find('.progressName');
  212 + var imageView = '?imageView2/1/w/100/h/100';
  213 +
  214 + var isImage = function(url) {
  215 + var res, suffix = "";
  216 + var imageSuffixes = ["png", "jpg", "jpeg", "gif", "bmp"];
  217 + var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;
  218 +
  219 + if (!url || !suffixMatch.test(url)) {
  220 + return false;
  221 + }
  222 + res = suffixMatch.exec(url);
  223 + suffix = res[1].toLowerCase();
  224 + for (var i = 0, l = imageSuffixes.length; i < l; i++) {
  225 + if (suffix === imageSuffixes[i]) {
  226 + return true;
  227 + }
  228 + }
  229 + return false;
  230 + };
  231 +
  232 + var isImg = isImage(url);
  233 +
  234 + var Wrapper = $('<div class="Wrapper"/>');
  235 + var imgWrapper = $('<div class="imgWrapper col-md-3"/>');
  236 + var linkWrapper = $('<a class="linkWrapper" target="_blank"/>');
  237 + var showImg = $('<img src="images/loading.gif"/>');
  238 +
  239 + progressNameTd.append(Wrapper);
  240 +
  241 + if (!isImg) {
  242 + showImg.attr('src', 'images/default.png');
  243 + Wrapper.addClass('default');
  244 +
  245 + imgWrapper.append(showImg);
  246 + Wrapper.append(imgWrapper);
  247 + } else {
  248 + linkWrapper.append(showImg);
  249 + imgWrapper.append(linkWrapper);
  250 + Wrapper.append(imgWrapper);
  251 +
  252 + var img = new Image();
  253 + if (!/imageView/.test(url)) {
  254 + url += imageView
  255 + }
  256 + $(img).attr('src', url);
  257 +
  258 + var height_space = 340;
  259 + $(img).on('load', function() {
  260 + showImg.attr('src', url);
  261 +
  262 + linkWrapper.attr('href', url).attr('title', '查看原图');
  263 +
  264 + function initImg(url, key, height) {
  265 + $('#myModal-img').modal();
  266 + var modalBody = $('#myModal-img').find('.modal-body');
  267 + if (height <= 300) {
  268 + $('#myModal-img').find('.text-warning').show();
  269 + }
  270 + var newImg = new Image();
  271 + modalBody.find('img').attr('src', 'images/loading.gif');
  272 + newImg.onload = function() {
  273 + modalBody.find('img').attr('src', url).data('key', key).data('h', height);
  274 + modalBody.find('.modal-body-wrapper').find('a').attr('href', url);
  275 + };
  276 + newImg.src = url;
  277 + }
  278 +
  279 + var infoWrapper = $('<div class="infoWrapper col-md-6"></div>');
  280 +
  281 +
  282 + var fopLink = $('<a class="fopLink"/>');
  283 + fopLink.attr('data-key', res.key).text('查看处理效果');
  284 + infoWrapper.append(fopLink);
  285 + fopLink.on('click', function() {
  286 + var key = $(this).data('key');
  287 + var height = parseInt($(this).parents('.Wrapper').find('.origin-height').text(), 10);
  288 + if (height > $(window).height() - height_space) {
  289 + height = parseInt($(window).height() - height_space, 10);
  290 + } else {
  291 + height = parseInt(height, 10) || 300;
  292 + //set a default height 300 for ie9-
  293 + }
  294 + var fopArr = [];
  295 + fopArr.push({
  296 + fop: 'imageView2',
  297 + mode: 3,
  298 + h: height,
  299 + q: 100,
  300 + format: 'png'
  301 + });
  302 + fopArr.push({
  303 + fop: 'watermark',
  304 + mode: 1,
  305 + image: 'http://www.b1.qiniudn.com/images/logo-2.png',
  306 + dissolve: 100,
  307 + gravity: 'SouthEast',
  308 + dx: 100,
  309 + dy: 100
  310 + });
  311 + var url = Qiniu.pipeline(fopArr, key);
  312 + $('#myModal-img').on('hide.bs.modal', function() {
  313 + $('#myModal-img').find('.btn-default').removeClass('disabled');
  314 + $('#myModal-img').find('.text-warning').hide();
  315 + }).on('show.bs.modal', function() {
  316 + $('#myModal-img').find('.imageView').find('a:eq(0)').addClass('disabled');
  317 + $('#myModal-img').find('.watermark').find('a:eq(3)').addClass('disabled');
  318 + $('#myModal-img').find('.text-warning').hide();
  319 + });
  320 +
  321 + initImg(url, key, height);
  322 +
  323 + return false;
  324 + });
  325 +
  326 + var ie = Qiniu.detectIEVersion();
  327 + if (!(ie && ie <= 9)) {
  328 + var exif = Qiniu.exif(res.key);
  329 + if (exif) {
  330 + var exifLink = $('<a href="" target="_blank">查看exif</a>');
  331 + exifLink.attr('href', url + '?exif');
  332 + infoWrapper.append(exifLink);
  333 + }
  334 +
  335 + var imageInfo = Qiniu.imageInfo(res.key);
  336 + var infoArea = $('<div/>');
  337 + var infoInner = '<div>格式:<span class="origin-format">' + imageInfo.format + '</span></div>' +
  338 + '<div>宽度:<span class="orgin-width">' + imageInfo.width + 'px</span></div>' +
  339 + '<div>高度:<span class="origin-height">' + imageInfo.height + 'px</span></div>';
  340 + infoArea.html(infoInner);
  341 +
  342 + infoWrapper.append(infoArea);
  343 + }
  344 +
  345 + Wrapper.append(infoWrapper);
  346 +
  347 + }).on('error', function() {
  348 + showImg.attr('src', 'default.png');
  349 + Wrapper.addClass('default');
  350 + });
  351 + }
  352 +};
  353 +FileProgress.prototype.setError = function() {
  354 + this.fileProgressWrapper.find('td:eq(2)').attr('class', 'text-warning');
  355 + this.fileProgressWrapper.find('td:eq(2) .progress').css('width', 0).hide();
  356 + this.fileProgressWrapper.find('button').hide();
  357 + this.fileProgressWrapper.next('.chunk-status-tr').hide();
  358 +};
  359 +
  360 +FileProgress.prototype.setCancelled = function(manual) {
  361 + var progressContainer = 'progressContainer';
  362 + if (!manual) {
  363 + progressContainer += ' red';
  364 + }
  365 + this.fileProgressWrapper.attr('class', progressContainer);
  366 + this.fileProgressWrapper.find('td .progress').remove();
  367 + this.fileProgressWrapper.find('td:eq(2) .btn-default').hide();
  368 + this.fileProgressWrapper.find('td:eq(2) .progressCancel').hide();
  369 +};
  370 +
  371 +FileProgress.prototype.setStatus = function(status, isUploading) {
  372 + if (!isUploading) {
  373 + this.fileProgressWrapper.find('.status').text(status).attr('class', 'status text-left');
  374 + }
  375 +};
  376 +
  377 +// 绑定取消上传事件
  378 +FileProgress.prototype.bindUploadCancel = function(up) {
  379 + var self = this;
  380 + if (up) {
  381 + self.fileProgressWrapper.find('td:eq(2) .progressCancel').on('click', function(){
  382 + self.setCancelled(false);
  383 + self.setStatus("取消上传");
  384 + self.fileProgressWrapper.find('.status').css('left', '0');
  385 + up.removeFile(self.file);
  386 + });
  387 + }
  388 +
  389 +};
  390 +
  391 +FileProgress.prototype.appear = function() {
  392 + if (this.getTimer() !== null) {
  393 + clearTimeout(this.getTimer());
  394 + this.setTimer(null);
  395 + }
  396 +
  397 + if (this.fileProgressWrapper[0].filters) {
  398 + try {
  399 + this.fileProgressWrapper[0].filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
  400 + } catch (e) {
  401 + // If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
  402 + this.fileProgressWrapper.css('filter', "progid:DXImageTransform.Microsoft.Alpha(opacity=100)");
  403 + }
  404 + } else {
  405 + this.fileProgressWrapper.css('opacity', 1);
  406 + }
  407 +
  408 + this.fileProgressWrapper.css('height', '');
  409 +
  410 + this.height = this.fileProgressWrapper.offset().top;
  411 + this.opacity = 100;
  412 + this.fileProgressWrapper.show();
  413 +
  414 +};
parent/center.manager/src/main/webapp/WEB-INF/static/js/qiniu.js View file @ a2758e4
Diff suppressed. Click to show
1   -/*!
2   - * qiniu-js-sdk v1.0.19
3   - *
4   - * Copyright 2015 by Qiniu
5   - * Released under GPL V2 License.
6   - *
7   - * GitHub: http://github.com/qiniu/js-sdk
8   - *
9   - * Date: 2017-3-15
10   -*/
11   -
12   -/*global plupload ,mOxie*/
13   -/*global ActiveXObject */
14   -/*exported Qiniu */
15   -/*exported QiniuJsSDK */
16   -
17   -;(function( global ){
18   -
19   -/**
20   - * Creates new cookie or removes cookie with negative expiration
21   - * @param key The key or identifier for the store
22   - * @param value Contents of the store
23   - * @param exp Expiration - creation defaults to 30 days
24   - */
25   -function createCookie(key, value, exp) {
26   - var date = new Date();
27   - date.setTime(date.getTime() + (exp * 24 * 60 * 60 * 1000));
28   - var expires = "; expires=" + date.toGMTString();
29   - document.cookie = key + "=" + value + expires + "; path=/";
30   -}
31   -
32   -/**
33   - * Returns contents of cookie
34   - * @param key The key or identifier for the store
35   - */
36   -function readCookie(key) {
37   - var nameEQ = key + "=";
38   - var ca = document.cookie.split(';');
39   - for (var i = 0, max = ca.length; i < max; i++) {
40   - var c = ca[i];
41   - while (c.charAt(0) === ' ') {
42   - c = c.substring(1, c.length);
43   - }
44   - if (c.indexOf(nameEQ) === 0) {
45   - return c.substring(nameEQ.length, c.length);
46   - }
47   - }
48   - return null;
49   -}
50   -
51   -// if current browser is not support localStorage
52   -// use cookie to make a polyfill
53   -if ( !window.localStorage ) {
54   - window.localStorage = {
55   - setItem: function (key, value) {
56   - createCookie(key, value, 30);
57   - },
58   - getItem: function (key) {
59   - return readCookie(key);
60   - },
61   - removeItem: function (key) {
62   - createCookie(key, '', -1);
63   - }
64   - };
65   -}
66   -
67   -function QiniuJsSDK() {
68   -
69   - var that = this;
70   -
71   - /**
72   - * detect IE version
73   - * if current browser is not IE
74   - * it will return false
75   - * else
76   - * it will return version of current IE browser
77   - * @return {Number|Boolean} IE version or false
78   - */
79   - this.detectIEVersion = function() {
80   - var v = 4,
81   - div = document.createElement('div'),
82   - all = div.getElementsByTagName('i');
83   - while (
84   - div.innerHTML = '<!--[if gt IE ' + v + ']><i></i><![endif]-->',
85   - all[0]
86   - ) {
87   - v++;
88   - }
89   - return v > 4 ? v : false;
90   - };
91   -
92   - var logger = {
93   - MUTE: 0,
94   - FATA: 1,
95   - ERROR: 2,
96   - WARN: 3,
97   - INFO: 4,
98   - DEBUG: 5,
99   - TRACE: 6,
100   - level: 0
101   - };
102   -
103   - function log(type, args){
104   - var header = "[qiniu-js-sdk]["+type+"]";
105   - var msg = header;
106   - for (var i = 0; i < args.length; i++) {
107   - if (typeof args[i] === "string") {
108   - msg += " " + args[i];
109   - } else {
110   - msg += " " + that.stringifyJSON(args[i]);
111   - }
112   - }
113   - if (that.detectIEVersion()) {
114   - // http://stackoverflow.com/questions/5538972/console-log-apply-not-working-in-ie9
115   - //var log = Function.prototype.bind.call(console.log, console);
116   - //log.apply(console, args);
117   - console.log(msg);
118   - }else{
119   - args.unshift(header);
120   - console.log.apply(console, args);
121   - }
122   - if (document.getElementById('qiniu-js-sdk-log')) {
123   - document.getElementById('qiniu-js-sdk-log').innerHTML += '<p>'+msg+'</p>';
124   - }
125   - }
126   -
127   - function makeLogFunc(code){
128   - var func = code.toLowerCase();
129   - logger[func] = function(){
130   - // logger[func].history = logger[func].history || [];
131   - // logger[func].history.push(arguments);
132   - if(window.console && window.console.log && logger.level>=logger[code]){
133   - var args = Array.prototype.slice.call(arguments);
134   - log(func,args);
135   - }
136   - };
137   - }
138   -
139   - for (var property in logger){
140   - if (logger.hasOwnProperty(property) && (typeof logger[property]) === "number" && !logger.hasOwnProperty(property.toLowerCase())) {
141   - makeLogFunc(property);
142   - }
143   - }
144   -
145   -
146   - var qiniuUploadUrl;
147   - if (window.location.protocol === 'https:') {
148   - qiniuUploadUrl = 'https://up.qbox.me';
149   - } else {
150   - qiniuUploadUrl = 'http://upload.qiniu.com';
151   - }
152   -
153   - /**
154   - * qiniu upload urls
155   - * 'qiniuUploadUrls' is used to change target when current url is not avaliable
156   - * @type {Array}
157   - */
158   - var qiniuUploadUrls = [
159   - "http://upload.qiniu.com",
160   - "http://up.qiniu.com"
161   - ];
162   -
163   - var qiniuUpHosts = {
164   - "http": [
165   - "http://upload.qiniu.com",
166   - "http://up.qiniu.com"
167   - ],
168   - "https": [
169   - "https://up.qbox.me"
170   - ]
171   - };
172   -
173   - var changeUrlTimes = 0;
174   -
175   - /**
176   - * reset upload url
177   - * if current page protocal is https
178   - * it will always return 'https://up.qbox.me'
179   - * else
180   - * it will set 'qiniuUploadUrl' value with 'qiniuUploadUrls' looply
181   - */
182   - this.resetUploadUrl = function(){
183   - var hosts = window.location.protocol === 'https:' ? qiniuUpHosts.https : qiniuUpHosts.http;
184   - var i = changeUrlTimes % hosts.length;
185   - qiniuUploadUrl = hosts[i];
186   - changeUrlTimes++;
187   - logger.debug('resetUploadUrl: '+qiniuUploadUrl);
188   - };
189   -
190   - // this.resetUploadUrl();
191   -
192   -
193   - /**
194   - * is image
195   - * @param {String} url of a file
196   - * @return {Boolean} file is a image or not
197   - */
198   - this.isImage = function(url) {
199   - url = url.split(/[?#]/)[0];
200   - return (/\.(png|jpg|jpeg|gif|bmp)$/i).test(url);
201   - };
202   -
203   - /**
204   - * get file extension
205   - * @param {String} filename
206   - * @return {String} file extension
207   - * @example
208   - * input: test.txt
209   - * output: txt
210   - */
211   - this.getFileExtension = function(filename) {
212   - var tempArr = filename.split(".");
213   - var ext;
214   - if (tempArr.length === 1 || (tempArr[0] === "" && tempArr.length === 2)) {
215   - ext = "";
216   - } else {
217   - ext = tempArr.pop().toLowerCase(); //get the extension and make it lower-case
218   - }
219   - return ext;
220   - };
221   -
222   - /**
223   - * encode string by utf8
224   - * @param {String} string to encode
225   - * @return {String} encoded string
226   - */
227   - this.utf8_encode = function(argString) {
228   - // http://kevin.vanzonneveld.net
229   - // + original by: Webtoolkit.info (http://www.webtoolkit.info/)
230   - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
231   - // + improved by: sowberry
232   - // + tweaked by: Jack
233   - // + bugfixed by: Onno Marsman
234   - // + improved by: Yves Sucaet
235   - // + bugfixed by: Onno Marsman
236   - // + bugfixed by: Ulrich
237   - // + bugfixed by: Rafal Kukawski
238   - // + improved by: kirilloid
239   - // + bugfixed by: kirilloid
240   - // * example 1: this.utf8_encode('Kevin van Zonneveld');
241   - // * returns 1: 'Kevin van Zonneveld'
242   -
243   - if (argString === null || typeof argString === 'undefined') {
244   - return '';
245   - }
246   -
247   - var string = (argString + ''); // .replace(/\r\n/g, '\n').replace(/\r/g, '\n');
248   - var utftext = '',
249   - start, end, stringl = 0;
250   -
251   - start = end = 0;
252   - stringl = string.length;
253   - for (var n = 0; n < stringl; n++) {
254   - var c1 = string.charCodeAt(n);
255   - var enc = null;
256   -
257   - if (c1 < 128) {
258   - end++;
259   - } else if (c1 > 127 && c1 < 2048) {
260   - enc = String.fromCharCode(
261   - (c1 >> 6) | 192, (c1 & 63) | 128
262   - );
263   - } else if (c1 & 0xF800 ^ 0xD800 > 0) {
264   - enc = String.fromCharCode(
265   - (c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
266   - );
267   - } else { // surrogate pairs
268   - if (c1 & 0xFC00 ^ 0xD800 > 0) {
269   - throw new RangeError('Unmatched trail surrogate at ' + n);
270   - }
271   - var c2 = string.charCodeAt(++n);
272   - if (c2 & 0xFC00 ^ 0xDC00 > 0) {
273   - throw new RangeError('Unmatched lead surrogate at ' + (n - 1));
274   - }
275   - c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
276   - enc = String.fromCharCode(
277   - (c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
278   - );
279   - }
280   - if (enc !== null) {
281   - if (end > start) {
282   - utftext += string.slice(start, end);
283   - }
284   - utftext += enc;
285   - start = end = n + 1;
286   - }
287   - }
288   -
289   - if (end > start) {
290   - utftext += string.slice(start, stringl);
291   - }
292   -
293   - return utftext;
294   - };
295   -
296   - this.base64_decode = function (data) {
297   - // http://kevin.vanzonneveld.net
298   - // + original by: Tyler Akins (http://rumkin.com)
299   - // + improved by: Thunder.m
300   - // + input by: Aman Gupta
301   - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
302   - // + bugfixed by: Onno Marsman
303   - // + bugfixed by: Pellentesque Malesuada
304   - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
305   - // + input by: Brett Zamir (http://brett-zamir.me)
306   - // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
307   - // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
308   - // * returns 1: 'Kevin van Zonneveld'
309   - // mozilla has this native
310   - // - but breaks in 2.0.0.12!
311   - //if (typeof this.window['atob'] == 'function') {
312   - // return atob(data);
313   - //}
314   - var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
315   - var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
316   - ac = 0,
317   - dec = "",
318   - tmp_arr = [];
319   -
320   - if (!data) {
321   - return data;
322   - }
323   -
324   - data += '';
325   -
326   - do { // unpack four hexets into three octets using index points in b64
327   - h1 = b64.indexOf(data.charAt(i++));
328   - h2 = b64.indexOf(data.charAt(i++));
329   - h3 = b64.indexOf(data.charAt(i++));
330   - h4 = b64.indexOf(data.charAt(i++));
331   -
332   - bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
333   -
334   - o1 = bits >> 16 & 0xff;
335   - o2 = bits >> 8 & 0xff;
336   - o3 = bits & 0xff;
337   -
338   - if (h3 === 64) {
339   - tmp_arr[ac++] = String.fromCharCode(o1);
340   - } else if (h4 === 64) {
341   - tmp_arr[ac++] = String.fromCharCode(o1, o2);
342   - } else {
343   - tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
344   - }
345   - } while (i < data.length);
346   -
347   - dec = tmp_arr.join('');
348   -
349   - return dec;
350   - };
351   -
352   - /**
353   - * encode data by base64
354   - * @param {String} data to encode
355   - * @return {String} encoded data
356   - */
357   - this.base64_encode = function(data) {
358   - // http://kevin.vanzonneveld.net
359   - // + original by: Tyler Akins (http://rumkin.com)
360   - // + improved by: Bayron Guevara
361   - // + improved by: Thunder.m
362   - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
363   - // + bugfixed by: Pellentesque Malesuada
364   - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
365   - // - depends on: this.utf8_encode
366   - // * example 1: this.base64_encode('Kevin van Zonneveld');
367   - // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
368   - // mozilla has this native
369   - // - but breaks in 2.0.0.12!
370   - //if (typeof this.window['atob'] == 'function') {
371   - // return atob(data);
372   - //}
373   - var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
374   - var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
375   - ac = 0,
376   - enc = '',
377   - tmp_arr = [];
378   -
379   - if (!data) {
380   - return data;
381   - }
382   -
383   - data = this.utf8_encode(data + '');
384   -
385   - do { // pack three octets into four hexets
386   - o1 = data.charCodeAt(i++);
387   - o2 = data.charCodeAt(i++);
388   - o3 = data.charCodeAt(i++);
389   -
390   - bits = o1 << 16 | o2 << 8 | o3;
391   -
392   - h1 = bits >> 18 & 0x3f;
393   - h2 = bits >> 12 & 0x3f;
394   - h3 = bits >> 6 & 0x3f;
395   - h4 = bits & 0x3f;
396   -
397   - // use hexets to index into b64, and append result to encoded string
398   - tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
399   - } while (i < data.length);
400   -
401   - enc = tmp_arr.join('');
402   -
403   - switch (data.length % 3) {
404   - case 1:
405   - enc = enc.slice(0, -2) + '==';
406   - break;
407   - case 2:
408   - enc = enc.slice(0, -1) + '=';
409   - break;
410   - }
411   -
412   - return enc;
413   - };
414   -
415   - /**
416   - * encode string in url by base64
417   - * @param {String} string in url
418   - * @return {String} encoded string
419   - */
420   - this.URLSafeBase64Encode = function(v) {
421   - v = this.base64_encode(v);
422   - return v.replace(/\//g, '_').replace(/\+/g, '-');
423   - };
424   -
425   - this.URLSafeBase64Decode = function(v) {
426   - v = v.replace(/_/g, '/').replace(/-/g, '+');
427   - return this.base64_decode(v);
428   - };
429   -
430   - // TODO: use mOxie
431   - /**
432   - * craete object used to AJAX
433   - * @return {Object}
434   - */
435   - this.createAjax = function(argument) {
436   - var xmlhttp = {};
437   - if (window.XMLHttpRequest) {
438   - xmlhttp = new XMLHttpRequest();
439   - } else {
440   - xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
441   - }
442   - return xmlhttp;
443   - };
444   -
445   - // TODO: enhance IE compatibility
446   - /**
447   - * parse json string to javascript object
448   - * @param {String} json string
449   - * @return {Object} object
450   - */
451   - this.parseJSON = function(data) {
452   - // Attempt to parse using the native JSON parser first
453   - if (window.JSON && window.JSON.parse) {
454   - return window.JSON.parse(data);
455   - }
456   -
457   - //var rx_one = /^[\],:{}\s]*$/,
458   - // rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
459   - // rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
460   - // rx_four = /(?:^|:|,)(?:\s*\[)+/g,
461   - var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
462   -
463   - //var json;
464   -
465   - var text = String(data);
466   - rx_dangerous.lastIndex = 0;
467   - if(rx_dangerous.test(text)){
468   - text = text.replace(rx_dangerous, function(a){
469   - return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
470   - });
471   - }
472   -
473   - // todo 使用一下判断,增加安全性
474   - //if (
475   - // rx_one.test(
476   - // text
477   - // .replace(rx_two, '@')
478   - // .replace(rx_three, ']')
479   - // .replace(rx_four, '')
480   - // )
481   - //) {
482   - // return eval('(' + text + ')');
483   - //}
484   -
485   - return eval('('+text+')');
486   - };
487   -
488   - /**
489   - * parse javascript object to json string
490   - * @param {Object} object
491   - * @return {String} json string
492   - */
493   - this.stringifyJSON = function(obj) {
494   - // Attempt to parse using the native JSON parser first
495   - if (window.JSON && window.JSON.stringify) {
496   - return window.JSON.stringify(obj);
497   - }
498   - switch (typeof (obj)) {
499   - case 'string':
500   - return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
501   - case 'array':
502   - return '[' + obj.map(that.stringifyJSON).join(',') + ']';
503   - case 'object':
504   - if (obj instanceof Array) {
505   - var strArr = [];
506   - var len = obj.length;
507   - for (var i = 0; i < len; i++) {
508   - strArr.push(that.stringifyJSON(obj[i]));
509   - }
510   - return '[' + strArr.join(',') + ']';
511   - } else if (obj === null) {
512   - return 'null';
513   - } else {
514   - var string = [];
515   - for (var property in obj) {
516   - if (obj.hasOwnProperty(property)) {
517   - string.push(that.stringifyJSON(property) + ':' + that.stringifyJSON(obj[property]));
518   - }
519   - }
520   - return '{' + string.join(',') + '}';
521   - }
522   - break;
523   - case 'number':
524   - return obj;
525   - case false:
526   - return obj;
527   - case 'boolean':
528   - return obj;
529   - }
530   - };
531   -
532   - /**
533   - * trim space beside text
534   - * @param {String} untrimed string
535   - * @return {String} trimed string
536   - */
537   - this.trim = function(text) {
538   - return text === null ? "" : text.replace(/^\s+|\s+$/g, '');
539   - };
540   -
541   - /**
542   - * create a uploader by QiniuJsSDK
543   - * @param {object} options to create a new uploader
544   - * @return {object} uploader
545   - */
546   - this.uploader = function(op) {
547   -
548   - /********** inner function define start **********/
549   -
550   - // according the different condition to reset chunk size
551   - // and the upload strategy according with the chunk size
552   - // when chunk size is zero will cause to direct upload
553   - // see the statement binded on 'BeforeUpload' event
554   - var reset_chunk_size = function() {
555   - var ie = that.detectIEVersion();
556   - var BLOCK_BITS, MAX_CHUNK_SIZE, chunk_size;
557   - // case Safari 5、Windows 7、iOS 7 set isSpecialSafari to true
558   - var isSpecialSafari = (mOxie.Env.browser === "Safari" && mOxie.Env.version <= 5 && mOxie.Env.os === "Windows" && mOxie.Env.osVersion === "7") || (mOxie.Env.browser === "Safari" && mOxie.Env.os === "iOS" && mOxie.Env.osVersion === "7");
559   - // case IE 9-,chunk_size is not empty and flash is included in runtimes
560   - // set op.chunk_size to zero
561   - //if (ie && ie < 9 && op.chunk_size && op.runtimes.indexOf('flash') >= 0) {
562   - if (ie && ie < 9 && op.chunk_size && op.runtimes.indexOf('flash') >= 0) {
563   - // link: http://www.plupload.com/docs/Frequently-Asked-Questions#when-to-use-chunking-and-when-not
564   - // when plupload chunk_size setting is't null ,it cause bug in ie8/9 which runs flash runtimes (not support html5) .
565   - op.chunk_size = 0;
566   - } else if (isSpecialSafari) {
567   - // win7 safari / iOS7 safari have bug when in chunk upload mode
568   - // reset chunk_size to 0
569   - // disable chunk in special version safari
570   - op.chunk_size = 0;
571   - } else {
572   - BLOCK_BITS = 20;
573   - MAX_CHUNK_SIZE = 4 << BLOCK_BITS; //4M
574   -
575   - chunk_size = plupload.parseSize(op.chunk_size);
576   - if (chunk_size > MAX_CHUNK_SIZE) {
577   - op.chunk_size = MAX_CHUNK_SIZE;
578   - }
579   - // qiniu service max_chunk_size is 4m
580   - // reset chunk_size to max_chunk_size(4m) when chunk_size > 4m
581   - }
582   - // if op.chunk_size set 0 will be cause to direct upload
583   - };
584   -
585   - var getHosts = function(hosts) {
586   - var result = [];
587   - for (var i = 0; i < hosts.length; i++) {
588   - var host = hosts[i];
589   - if (host.indexOf('-H') === 0) {
590   - result.push(host.split(' ')[2]);
591   - } else {
592   - result.push(host);
593   - }
594   - }
595   - return result;
596   - };
597   -
598   - var getPutPolicy = function (uptoken) {
599   - var segments = uptoken.split(":");
600   - var ak = segments[0];
601   - var putPolicy = that.parseJSON(that.URLSafeBase64Decode(segments[2]));
602   - putPolicy.ak = ak;
603   - if (putPolicy.scope.indexOf(":") >= 0) {
604   - putPolicy.bucket = putPolicy.scope.split(":")[0];
605   - putPolicy.key = putPolicy.scope.split(":")[1];
606   - } else {
607   - putPolicy.bucket = putPolicy.scope;
608   - }
609   - return putPolicy;
610   - };
611   -
612   - var getUpHosts = function(uptoken) {
613   - var putPolicy = getPutPolicy(uptoken);
614   - // var uphosts_url = "//uc.qbox.me/v1/query?ak="+ak+"&bucket="+putPolicy.scope;
615   - // IE 9- is not support protocal relative url
616   - var uphosts_url = window.location.protocol + "//uc.qbox.me/v1/query?ak=" + putPolicy.ak + "&bucket=" + putPolicy.bucket;
617   - logger.debug("putPolicy: ", putPolicy);
618   - logger.debug("get uphosts from: ", uphosts_url);
619   - var ie = that.detectIEVersion();
620   - var ajax;
621   - if (ie && ie <= 9) {
622   - ajax = new mOxie.XMLHttpRequest();
623   - mOxie.Env.swf_url = op.flash_swf_url;
624   - }else{
625   - ajax = that.createAjax();
626   - }
627   - ajax.open('GET', uphosts_url, false);
628   - var onreadystatechange = function(){
629   - logger.debug("ajax.readyState: ", ajax.readyState);
630   - if (ajax.readyState === 4) {
631   - logger.debug("ajax.status: ", ajax.status);
632   - if (ajax.status < 400) {
633   - var res = that.parseJSON(ajax.responseText);
634   - qiniuUpHosts.http = getHosts(res.http.up);
635   - qiniuUpHosts.https = getHosts(res.https.up);
636   - logger.debug("get new uphosts: ", qiniuUpHosts);
637   - that.resetUploadUrl();
638   - } else {
639   - logger.error("get uphosts error: ", ajax.responseText);
640   - }
641   - }
642   - };
643   - if (ie && ie <= 9) {
644   - ajax.bind('readystatechange', onreadystatechange);
645   - }else{
646   - ajax.onreadystatechange = onreadystatechange;
647   - }
648   - ajax.send();
649   - // ajax.send();
650   - // if (ajax.status < 400) {
651   - // var res = that.parseJSON(ajax.responseText);
652   - // qiniuUpHosts.http = getHosts(res.http.up);
653   - // qiniuUpHosts.https = getHosts(res.https.up);
654   - // logger.debug("get new uphosts: ", qiniuUpHosts);
655   - // that.resetUploadUrl();
656   - // } else {
657   - // logger.error("get uphosts error: ", ajax.responseText);
658   - // }
659   - return;
660   - };
661   -
662   - var getUptoken = function(file) {
663   - if (!that.token || (op.uptoken_url && that.tokenInfo.isExpired())) {
664   - return getNewUpToken(file);
665   - } else {
666   - return that.token;
667   - }
668   - };
669   -
670   - // getNewUptoken maybe called at Init Event or BeforeUpload Event
671   - // case Init Event, the file param of getUptken will be set a null value
672   - // if op.uptoken has value, set uptoken with op.uptoken
673   - // else if op.uptoken_url has value, set uptoken from op.uptoken_url
674   - // else if op.uptoken_func has value, set uptoken by result of op.uptoken_func
675   - var getNewUpToken = function(file) {
676   - if (op.uptoken) {
677   - that.token = op.uptoken;
678   - } else if (op.uptoken_url) {
679   - logger.debug("get uptoken from: ", that.uptoken_url);
680   - // TODO: use mOxie
681   - var ajax = that.createAjax();
682   - ajax.open('GET', that.uptoken_url, false);
683   - ajax.setRequestHeader("If-Modified-Since", "0");
684   - // ajax.onreadystatechange = function() {
685   - // if (ajax.readyState === 4 && ajax.status === 200) {
686   - // var res = that.parseJSON(ajax.responseText);
687   - // that.token = res.uptoken;
688   - // }
689   - // };
690   - ajax.send();
691   - if (ajax.status === 200) {
692   - var res = that.parseJSON(ajax.responseText);
693   - that.token = res.uptoken;
694   - var segments = that.token.split(":");
695   - var putPolicy = that.parseJSON(that.URLSafeBase64Decode(segments[2]));
696   - if (!that.tokenMap) {
697   - that.tokenMap = {};
698   - }
699   - var getTimestamp = function(time) {
700   - return Math.ceil(time.getTime()/1000);
701   - };
702   - var serverTime = getTimestamp(new Date(ajax.getResponseHeader("date")));
703   - var clientTime = getTimestamp(new Date());
704   - that.tokenInfo = {
705   - serverDelay: clientTime - serverTime,
706   - deadline: putPolicy.deadline,
707   - isExpired: function() {
708   - var leftTime = this.deadline - getTimestamp(new Date()) + this.serverDelay;
709   - return leftTime < 600;
710   - }
711   - };
712   - logger.debug("get new uptoken: ", that.token);
713   - logger.debug("get token info: ", that.tokenInfo);
714   - } else {
715   - logger.error("get uptoken error: ", ajax.responseText);
716   - }
717   - } else if (op.uptoken_func) {
718   - logger.debug("get uptoken from uptoken_func");
719   - that.token = op.uptoken_func(file);
720   - logger.debug("get new uptoken: ", that.token);
721   - } else {
722   - logger.error("one of [uptoken, uptoken_url, uptoken_func] settings in options is required!");
723   - }
724   - if (that.token) {
725   - getUpHosts(that.token);
726   - }
727   - return that.token;
728   - };
729   -
730   - // get file key according with the user passed options
731   - var getFileKey = function(up, file, func) {
732   - // WARNING
733   - // When you set the key in putPolicy by "scope": "bucket:key"
734   - // You should understand the risk of override a file in the bucket
735   - // So the code below that automatically get key from uptoken has been commented
736   - // var putPolicy = getPutPolicy(that.token)
737   - // if (putPolicy.key) {
738   - // logger.debug("key is defined in putPolicy.scope: ", putPolicy.key)
739   - // return putPolicy.key
740   - // }
741   - var key = '',
742   - unique_names = false;
743   - if (!op.save_key) {
744   - unique_names = up.getOption && up.getOption('unique_names');
745   - unique_names = unique_names || (up.settings && up.settings.unique_names);
746   - if (unique_names) {
747   - var ext = that.getFileExtension(file.name);
748   - key = ext ? file.id + '.' + ext : file.id;
749   - } else if (typeof func === 'function') {
750   - key = func(up, file);
751   - } else {
752   - key = file.name;
753   - }
754   - }
755   - return key;
756   - };
757   -
758   - /********** inner function define end **********/
759   -
760   - if (op.log_level) {
761   - logger.level = op.log_level;
762   - }
763   -
764   - if (!op.domain) {
765   - throw 'domain setting in options is required!';
766   - }
767   -
768   - if (!op.browse_button) {
769   - throw 'browse_button setting in options is required!';
770   - }
771   -
772   - if (!op.uptoken && !op.uptoken_url && !op.uptoken_func) {
773   - throw 'one of [uptoken, uptoken_url, uptoken_func] settings in options is required!';
774   - }
775   -
776   - logger.debug("init uploader start");
777   -
778   - logger.debug("environment: ", mOxie.Env);
779   -
780   - logger.debug("userAgent: ", navigator.userAgent);
781   -
782   - var option = {};
783   -
784   - // hold the handler from user passed options
785   - var _Error_Handler = op.init && op.init.Error;
786   - var _FileUploaded_Handler = op.init && op.init.FileUploaded;
787   -
788   - // replace the handler for intercept
789   - op.init.Error = function() {};
790   - op.init.FileUploaded = function() {};
791   -
792   - that.uptoken_url = op.uptoken_url;
793   - that.token = '';
794   - that.key_handler = typeof op.init.Key === 'function' ? op.init.Key : '';
795   - this.domain = op.domain;
796   - // TODO: ctx is global in scope of a uploader instance
797   - // this maybe cause error
798   - var ctx = '';
799   - var speedCalInfo = {
800   - isResumeUpload: false,
801   - resumeFilesize: 0,
802   - startTime: '',
803   - currentTime: ''
804   - };
805   -
806   - reset_chunk_size();
807   - logger.debug("invoke reset_chunk_size()");
808   - logger.debug("op.chunk_size: ", op.chunk_size);
809   -
810   - var defaultSetting = {
811   - url: qiniuUploadUrl,
812   - multipart_params: {
813   - token: ''
814   - }
815   - };
816   - var ie = that.detectIEVersion();
817   - // case IE 9-
818   - // add accept in multipart params
819   - if (ie && ie <= 9) {
820   - defaultSetting.multipart_params.accept = 'text/plain; charset=utf-8';
821   - logger.debug("add accept text/plain in multipart params");
822   - }
823   -
824   - // compose options with user passed options and default setting
825   - plupload.extend(option, op, defaultSetting);
826   -
827   - logger.debug("option: ", option);
828   -
829   - // create a new uploader with composed options
830   - var uploader = new plupload.Uploader(option);
831   -
832   - logger.debug("new plupload.Uploader(option)");
833   -
834   - // bind getNewUpToken to 'Init' event
835   - uploader.bind('Init', function(up, params) {
836   - logger.debug("Init event activated");
837   - // if op.get_new_uptoken is not true
838   - // invoke getNewUptoken when uploader init
839   - // else
840   - // getNewUptoken everytime before a new file upload
841   - if(!op.get_new_uptoken){
842   - getNewUpToken(null);
843   - }
844   - //getNewUpToken(null);
845   - });
846   -
847   - logger.debug("bind Init event");
848   -
849   - // bind 'FilesAdded' event
850   - // when file be added and auto_start has set value
851   - // uploader will auto start upload the file
852   - uploader.bind('FilesAdded', function(up, files) {
853   - logger.debug("FilesAdded event activated");
854   - var auto_start = up.getOption && up.getOption('auto_start');
855   - auto_start = auto_start || (up.settings && up.settings.auto_start);
856   - logger.debug("auto_start: ", auto_start);
857   - logger.debug("files: ", files);
858   -
859   - // detect is iOS
860   - var is_ios = function (){
861   - if(mOxie.Env.OS.toLowerCase()==="ios") {
862   - return true;
863   - } else {
864   - return false;
865   - }
866   - };
867   -
868   - // if current env os is iOS change file name to [time].[ext]
869   - if (is_ios()) {
870   - for (var i = 0; i < files.length; i++) {
871   - var file = files[i];
872   - var ext = that.getFileExtension(file.name);
873   - file.name = file.id + "." + ext;
874   - }
875   - }
876   -
877   - if (auto_start) {
878   - setTimeout(function(){
879   - up.start();
880   - logger.debug("invoke up.start()");
881   - }, 0);
882   - // up.start();
883   - // plupload.each(files, function(i, file) {
884   - // up.start();
885   - // logger.debug("invoke up.start()")
886   - // logger.debug("file: ", file);
887   - // });
888   - }
889   - up.refresh(); // Reposition Flash/Silverlight
890   - });
891   -
892   - logger.debug("bind FilesAdded event");
893   -
894   - // bind 'BeforeUpload' event
895   - // intercept the process of upload
896   - // - prepare uptoken
897   - // - according the chunk size to make differnt upload strategy
898   - // - resume upload with the last breakpoint of file
899   - uploader.bind('BeforeUpload', function(up, file) {
900   - logger.debug("BeforeUpload event activated");
901   - // add a key named speed for file object
902   - file.speed = file.speed || 0;
903   - ctx = '';
904   -
905   - if(op.get_new_uptoken){
906   - getNewUpToken(file);
907   - }
908   -
909   - var directUpload = function(up, file, func) {
910   - speedCalInfo.startTime = new Date().getTime();
911   - var multipart_params_obj;
912   - if (op.save_key) {
913   - multipart_params_obj = {
914   - 'token': that.token
915   - };
916   - } else {
917   - multipart_params_obj = {
918   - 'key': getFileKey(up, file, func),
919   - 'token': that.token
920   - };
921   - }
922   - var ie = that.detectIEVersion();
923   - // case IE 9-
924   - // add accept in multipart params
925   - if (ie && ie <= 9) {
926   - multipart_params_obj.accept = 'text/plain; charset=utf-8';
927   - logger.debug("add accept text/plain in multipart params");
928   - }
929   -
930   - logger.debug("directUpload multipart_params_obj: ", multipart_params_obj);
931   -
932   - var x_vars = op.x_vars;
933   - if (x_vars !== undefined && typeof x_vars === 'object') {
934   - for (var x_key in x_vars) {
935   - if (x_vars.hasOwnProperty(x_key)) {
936   - if (typeof x_vars[x_key] === 'function') {
937   - multipart_params_obj['x:' + x_key] = x_vars[x_key](up, file);
938   - } else if (typeof x_vars[x_key] !== 'object') {
939   - multipart_params_obj['x:' + x_key] = x_vars[x_key];
940   - }
941   - }
942   - }
943   - }
944   -
945   - up.setOption({
946   - 'url': qiniuUploadUrl,
947   - 'multipart': true,
948   - 'chunk_size': is_android_weixin_or_qq() ? op.max_file_size : undefined,
949   - 'multipart_params': multipart_params_obj
950   - });
951   - };
952   -
953   - // detect is weixin or qq inner browser
954   - var is_android_weixin_or_qq = function (){
955   - var ua = navigator.userAgent.toLowerCase();
956   - if((ua.match(/MicroMessenger/i) || mOxie.Env.browser === "QQBrowser" || ua.match(/V1_AND_SQ/i)) && mOxie.Env.OS.toLowerCase()==="android") {
957   - return true;
958   - } else {
959   - return false;
960   - }
961   - };
962   -
963   - var chunk_size = up.getOption && up.getOption('chunk_size');
964   - chunk_size = chunk_size || (up.settings && up.settings.chunk_size);
965   -
966   - logger.debug("uploader.runtime: ",uploader.runtime);
967   - logger.debug("chunk_size: ",chunk_size);
968   -
969   - // TODO: flash support chunk upload
970   - if ((uploader.runtime === 'html5' || uploader.runtime === 'flash') && chunk_size) {
971   - if (file.size < chunk_size || is_android_weixin_or_qq()) {
972   - logger.debug("directUpload because file.size < chunk_size || is_android_weixin_or_qq()");
973   - // direct upload if file size is less then the chunk size
974   - directUpload(up, file, that.key_handler);
975   - } else {
976   - // TODO: need a polifill to make it work in IE 9-
977   - // ISSUE: if file.name is existed in localStorage
978   - // but not the same file maybe cause error
979   - var localFileInfo = localStorage.getItem(file.name);
980   - var blockSize = chunk_size;
981   - if (localFileInfo) {
982   - // TODO: although only the html5 runtime will enter this statement
983   - // but need uniform way to make convertion between string and json
984   - localFileInfo = that.parseJSON(localFileInfo);
985   - var now = (new Date()).getTime();
986   - var before = localFileInfo.time || 0;
987   - var aDay = 24 * 60 * 60 * 1000; // milliseconds of one day
988   - // if the last upload time is within one day
989   - // will upload continuously follow the last breakpoint
990   - // else
991   - // will reupload entire file
992   - if (now - before < aDay) {
993   -
994   - if (localFileInfo.percent !== 100) {
995   - if (file.size === localFileInfo.total) {
996   - // TODO: if file.name and file.size is the same
997   - // but not the same file will cause error
998   - file.percent = localFileInfo.percent;
999   - file.loaded = localFileInfo.offset;
1000   - ctx = localFileInfo.ctx;
1001   -
1002   - // set speed info
1003   - speedCalInfo.isResumeUpload = true;
1004   - speedCalInfo.resumeFilesize = localFileInfo.offset;
1005   -
1006   - // set block size
1007   - if (localFileInfo.offset + blockSize > file.size) {
1008   - blockSize = file.size - localFileInfo.offset;
1009   - }
1010   - } else {
1011   - // remove file info when file.size is conflict with file info
1012   - localStorage.removeItem(file.name);
1013   - }
1014   -
1015   - } else {
1016   - // remove file info when upload percent is 100%
1017   - // avoid 499 bug
1018   - localStorage.removeItem(file.name);
1019   - }
1020   - } else {
1021   - // remove file info when last upload time is over one day
1022   - localStorage.removeItem(file.name);
1023   - }
1024   - }
1025   - speedCalInfo.startTime = new Date().getTime();
1026   - var multipart_params_obj = {};
1027   - var ie = that.detectIEVersion();
1028   - // case IE 9-
1029   - // add accept in multipart params
1030   - if (ie && ie <= 9) {
1031   - multipart_params_obj.accept = 'text/plain; charset=utf-8';
1032   - logger.debug("add accept text/plain in multipart params");
1033   - }
1034   - // TODO: to support bput
1035   - // http://developer.qiniu.com/docs/v6/api/reference/up/bput.html
1036   - up.setOption({
1037   - 'url': qiniuUploadUrl + '/mkblk/' + blockSize,
1038   - 'multipart': false,
1039   - 'chunk_size': chunk_size,
1040   - 'required_features': "chunks",
1041   - 'headers': {
1042   - 'Authorization': 'UpToken ' + getUptoken(file)
1043   - },
1044   - 'multipart_params': multipart_params_obj
1045   - });
1046   - }
1047   - } else {
1048   - logger.debug("directUpload because uploader.runtime !== 'html5' || uploader.runtime !== 'flash' || !chunk_size");
1049   - // direct upload if runtime is not html5
1050   - directUpload(up, file, that.key_handler);
1051   - }
1052   - });
1053   -
1054   - logger.debug("bind BeforeUpload event");
1055   -
1056   - // bind 'UploadProgress' event
1057   - // calculate upload speed
1058   - uploader.bind('UploadProgress', function(up, file) {
1059   - logger.trace("UploadProgress event activated");
1060   - speedCalInfo.currentTime = new Date().getTime();
1061   - var timeUsed = speedCalInfo.currentTime - speedCalInfo.startTime; // ms
1062   - var fileUploaded = file.loaded || 0;
1063   - if (speedCalInfo.isResumeUpload) {
1064   - fileUploaded = file.loaded - speedCalInfo.resumeFilesize;
1065   - }
1066   - file.speed = (fileUploaded / timeUsed * 1000).toFixed(0) || 0; // unit: byte/s
1067   - });
1068   -
1069   - logger.debug("bind UploadProgress event");
1070   -
1071   - // bind 'ChunkUploaded' event
1072   - // store the chunk upload info and set next chunk upload url
1073   - uploader.bind('ChunkUploaded', function(up, file, info) {
1074   - logger.debug("ChunkUploaded event activated");
1075   - logger.debug("file: ", file);
1076   - logger.debug("info: ", info);
1077   - var res = that.parseJSON(info.response);
1078   - logger.debug("res: ", res);
1079   - // ctx should look like '[chunk01_ctx],[chunk02_ctx],[chunk03_ctx],...'
1080   - ctx = ctx ? ctx + ',' + res.ctx : res.ctx;
1081   - var leftSize = info.total - info.offset;
1082   - var chunk_size = up.getOption && up.getOption('chunk_size');
1083   - chunk_size = chunk_size || (up.settings && up.settings.chunk_size);
1084   - if (leftSize < chunk_size) {
1085   - up.setOption({
1086   - 'url': qiniuUploadUrl + '/mkblk/' + leftSize
1087   - });
1088   - logger.debug("up.setOption url: ", qiniuUploadUrl + '/mkblk/' + leftSize);
1089   - }
1090   - up.setOption({
1091   - 'headers': {
1092   - 'Authorization': 'UpToken ' + getUptoken(file)
1093   - }
1094   - });
1095   - localStorage.setItem(file.name, that.stringifyJSON({
1096   - ctx: ctx,
1097   - percent: file.percent,
1098   - total: info.total,
1099   - offset: info.offset,
1100   - time: (new Date()).getTime()
1101   - }));
1102   - });
1103   -
1104   - logger.debug("bind ChunkUploaded event");
1105   -
1106   - var retries = qiniuUploadUrls.length;
1107   -
1108   - // if error is unkown switch upload url and retry
1109   - var unknow_error_retry = function(file){
1110   - if (retries-- > 0) {
1111   - setTimeout(function(){
1112   - that.resetUploadUrl();
1113   - file.status = plupload.QUEUED;
1114   - uploader.stop();
1115   - uploader.start();
1116   - }, 0);
1117   - return true;
1118   - }else{
1119   - retries = qiniuUploadUrls.length;
1120   - return false;
1121   - }
1122   - };
1123   -
1124   - // bind 'Error' event
1125   - // check the err.code and return the errTip
1126   - uploader.bind('Error', (function(_Error_Handler) {
1127   - return function(up, err) {
1128   - logger.error("Error event activated");
1129   - logger.error("err: ", err);
1130   - var errTip = '';
1131   - var file = err.file;
1132   - if (file) {
1133   - switch (err.code) {
1134   - case plupload.FAILED:
1135   - errTip = '上传失败。请稍后再试。';
1136   - break;
1137   - case plupload.FILE_SIZE_ERROR:
1138   - var max_file_size = up.getOption && up.getOption('max_file_size');
1139   - max_file_size = max_file_size || (up.settings && up.settings.max_file_size);
1140   - errTip = '浏览器最大可上传' + max_file_size + '。更大文件请使用命令行工具。';
1141   - break;
1142   - case plupload.FILE_EXTENSION_ERROR:
1143   - errTip = '文件验证失败。请稍后重试。';
1144   - break;
1145   - case plupload.HTTP_ERROR:
1146   - if (err.response === '') {
1147   - // Fix parseJSON error ,when http error is like net::ERR_ADDRESS_UNREACHABLE
1148   - errTip = err.message || '未知网络错误。';
1149   - if (!unknow_error_retry(file)) {
1150   - return;
1151   - }
1152   - break;
1153   - }
1154   - var errorObj = that.parseJSON(err.response);
1155   - var errorText = errorObj.error;
1156   - switch (err.status) {
1157   - case 400:
1158   - errTip = "请求报文格式错误。";
1159   - break;
1160   - case 401:
1161   - errTip = "客户端认证授权失败。请重试或提交反馈。";
1162   - break;
1163   - case 405:
1164   - errTip = "客户端请求错误。请重试或提交反馈。";
1165   - break;
1166   - case 579:
1167   - errTip = "资源上传成功,但回调失败。";
1168   - break;
1169   - case 599:
1170   - errTip = "网络连接异常。请重试或提交反馈。";
1171   - if (!unknow_error_retry(file)) {
1172   - return;
1173   - }
1174   - break;
1175   - case 614:
1176   - errTip = "文件已存在。";
1177   - try {
1178   - errorObj = that.parseJSON(errorObj.error);
1179   - errorText = errorObj.error || 'file exists';
1180   - } catch (e) {
1181   - errorText = errorObj.error || 'file exists';
1182   - }
1183   - break;
1184   - case 631:
1185   - errTip = "指定空间不存在。";
1186   - break;
1187   - case 701:
1188   - errTip = "上传数据块校验出错。请重试或提交反馈。";
1189   - break;
1190   - default:
1191   - errTip = "未知错误。";
1192   - if (!unknow_error_retry(file)) {
1193   - return;
1194   - }
1195   - break;
1196   - }
1197   - errTip = errTip + '(' + err.status + ':' + errorText + ')';
1198   - break;
1199   - case plupload.SECURITY_ERROR:
1200   - errTip = '安全配置错误。请联系网站管理员。';
1201   - break;
1202   - case plupload.GENERIC_ERROR:
1203   - errTip = '上传失败。请稍后再试。';
1204   - break;
1205   - case plupload.IO_ERROR:
1206   - errTip = '上传失败。请稍后再试。';
1207   - break;
1208   - case plupload.INIT_ERROR:
1209   - errTip = '网站配置错误。请联系网站管理员。';
1210   - uploader.destroy();
1211   - break;
1212   - default:
1213   - errTip = err.message + err.details;
1214   - if (!unknow_error_retry(file)) {
1215   - return;
1216   - }
1217   - break;
1218   - }
1219   - if (_Error_Handler) {
1220   - _Error_Handler(up, err, errTip);
1221   - }
1222   - }
1223   - up.refresh(); // Reposition Flash/Silverlight
1224   - };
1225   - })(_Error_Handler));
1226   -
1227   - logger.debug("bind Error event");
1228   -
1229   - // bind 'FileUploaded' event
1230   - // intercept the complete of upload
1231   - // - get downtoken from downtoken_url if bucket is private
1232   - // - invoke mkfile api to compose chunks if upload strategy is chunk upload
1233   - uploader.bind('FileUploaded', (function(_FileUploaded_Handler) {
1234   - return function(up, file, info) {
1235   - logger.debug("FileUploaded event activated");
1236   - logger.debug("file: ", file);
1237   - logger.debug("info: ", info);
1238   - var last_step = function(up, file, info) {
1239   - if (op.downtoken_url) {
1240   - // if op.dowontoken_url is not empty
1241   - // need get downtoken before invoke the _FileUploaded_Handler
1242   - var ajax_downtoken = that.createAjax();
1243   - ajax_downtoken.open('POST', op.downtoken_url, true);
1244   - ajax_downtoken.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
1245   - ajax_downtoken.onreadystatechange = function() {
1246   - if (ajax_downtoken.readyState === 4) {
1247   - if (ajax_downtoken.status === 200) {
1248   - var res_downtoken;
1249   - try {
1250   - res_downtoken = that.parseJSON(ajax_downtoken.responseText);
1251   - } catch (e) {
1252   - throw ('invalid json format');
1253   - }
1254   - var info_extended = {};
1255   - plupload.extend(info_extended, that.parseJSON(info), res_downtoken);
1256   - if (_FileUploaded_Handler) {
1257   - _FileUploaded_Handler(up, file, that.stringifyJSON(info_extended));
1258   - }
1259   - } else {
1260   - uploader.trigger('Error', {
1261   - status: ajax_downtoken.status,
1262   - response: ajax_downtoken.responseText,
1263   - file: file,
1264   - code: plupload.HTTP_ERROR
1265   - });
1266   - }
1267   - }
1268   - };
1269   - ajax_downtoken.send('key=' + that.parseJSON(info).key + '&domain=' + op.domain);
1270   - } else if (_FileUploaded_Handler) {
1271   - _FileUploaded_Handler(up, file, info);
1272   - }
1273   - };
1274   -
1275   - var res = that.parseJSON(info.response);
1276   - ctx = ctx ? ctx : res.ctx;
1277   - // if ctx is not empty
1278   - // that means the upload strategy is chunk upload
1279   - // befroe the invoke the last_step
1280   - // we need request the mkfile to compose all uploaded chunks
1281   - // else
1282   - // invalke the last_step
1283   - logger.debug("ctx: ", ctx);
1284   - if (ctx) {
1285   - var key = '';
1286   - logger.debug("save_key: ", op.save_key);
1287   - if (!op.save_key) {
1288   - key = getFileKey(up, file, that.key_handler);
1289   - key = key ? '/key/' + that.URLSafeBase64Encode(key) : '';
1290   - }
1291   -
1292   - var fname = '/fname/' + that.URLSafeBase64Encode(file.name);
1293   -
1294   - logger.debug("op.x_vars: ", op.x_vars);
1295   - var x_vars = op.x_vars,
1296   - x_val = '',
1297   - x_vars_url = '';
1298   - if (x_vars !== undefined && typeof x_vars === 'object') {
1299   - for (var x_key in x_vars) {
1300   - if (x_vars.hasOwnProperty(x_key)) {
1301   - if (typeof x_vars[x_key] === 'function') {
1302   - x_val = that.URLSafeBase64Encode(x_vars[x_key](up, file));
1303   - } else if (typeof x_vars[x_key] !== 'object') {
1304   - x_val = that.URLSafeBase64Encode(x_vars[x_key]);
1305   - }
1306   - x_vars_url += '/x:' + x_key + '/' + x_val;
1307   - }
1308   - }
1309   - }
1310   -
1311   - var url = qiniuUploadUrl + '/mkfile/' + file.size + key + fname + x_vars_url;
1312   -
1313   - var ie = that.detectIEVersion();
1314   - var ajax;
1315   - if (ie && ie <= 9) {
1316   - ajax = new mOxie.XMLHttpRequest();
1317   - mOxie.Env.swf_url = op.flash_swf_url;
1318   - }else{
1319   - ajax = that.createAjax();
1320   - }
1321   - ajax.open('POST', url, true);
1322   - ajax.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
1323   - ajax.setRequestHeader('Authorization', 'UpToken ' + that.token);
1324   - var onreadystatechange = function(){
1325   - logger.debug("ajax.readyState: ", ajax.readyState);
1326   - if (ajax.readyState === 4) {
1327   - localStorage.removeItem(file.name);
1328   - var info;
1329   - if (ajax.status === 200) {
1330   - info = ajax.responseText;
1331   - logger.debug("mkfile is success: ", info);
1332   - last_step(up, file, info);
1333   - } else {
1334   - info = {
1335   - status: ajax.status,
1336   - response: ajax.responseText,
1337   - file: file,
1338   - code: -200,
1339   - responseHeaders: ajax.getAllResponseHeaders()
1340   - };
1341   - logger.debug("mkfile is error: ", info);
1342   - uploader.trigger('Error', info);
1343   - }
1344   - }
1345   - };
1346   - if (ie && ie <= 9) {
1347   - ajax.bind('readystatechange', onreadystatechange);
1348   - }else{
1349   - ajax.onreadystatechange = onreadystatechange;
1350   - }
1351   - ajax.send(ctx);
1352   - logger.debug("mkfile: ", url);
1353   - } else {
1354   - last_step(up, file, info.response);
1355   - }
1356   -
1357   - };
1358   - })(_FileUploaded_Handler));
1359   -
1360   - logger.debug("bind FileUploaded event");
1361   -
1362   - // init uploader
1363   - uploader.init();
1364   -
1365   - logger.debug("invoke uploader.init()");
1366   -
1367   - logger.debug("init uploader end");
1368   -
1369   - return uploader;
1370   - };
1371   -
1372   - /**
1373   - * get url by key
1374   - * @param {String} key of file
1375   - * @return {String} url of file
1376   - */
1377   - this.getUrl = function(key) {
1378   - if (!key) {
1379   - return false;
1380   - }
1381   - key = encodeURI(key);
1382   - var domain = this.domain;
1383   - if (domain.slice(domain.length - 1) !== '/') {
1384   - domain = domain + '/';
1385   - }
1386   - return domain + key;
1387   - };
1388   -
1389   - /**
1390   - * invoke the imageView2 api of Qiniu
1391   - * @param {Object} api params
1392   - * @param {String} key of file
1393   - * @return {String} url of processed image
1394   - */
1395   - this.imageView2 = function(op, key) {
1396   -
1397   - if (!/^\d$/.test(op.mode)) {
1398   - return false;
1399   - }
1400   -
1401   - var mode = op.mode,
1402   - w = op.w || '',
1403   - h = op.h || '',
1404   - q = op.q || '',
1405   - format = op.format || '';
1406   -
1407   - if (!w && !h) {
1408   - return false;
1409   - }
1410   -
1411   - var imageUrl = 'imageView2/' + mode;
1412   - imageUrl += w ? '/w/' + w : '';
1413   - imageUrl += h ? '/h/' + h : '';
1414   - imageUrl += q ? '/q/' + q : '';
1415   - imageUrl += format ? '/format/' + format : '';
1416   - if (key) {
1417   - imageUrl = this.getUrl(key) + '?' + imageUrl;
1418   - }
1419   - return imageUrl;
1420   - };
1421   -
1422   - /**
1423   - * invoke the imageMogr2 api of Qiniu
1424   - * @param {Object} api params
1425   - * @param {String} key of file
1426   - * @return {String} url of processed image
1427   - */
1428   - this.imageMogr2 = function(op, key) {
1429   - var auto_orient = op['auto-orient'] || '',
1430   - thumbnail = op.thumbnail || '',
1431   - strip = op.strip || '',
1432   - gravity = op.gravity || '',
1433   - crop = op.crop || '',
1434   - quality = op.quality || '',
1435   - rotate = op.rotate || '',
1436   - format = op.format || '',
1437   - blur = op.blur || '';
1438   - //Todo check option
1439   -
1440   - var imageUrl = 'imageMogr2';
1441   -
1442   - imageUrl += auto_orient ? '/auto-orient' : '';
1443   - imageUrl += thumbnail ? '/thumbnail/' + thumbnail : '';
1444   - imageUrl += strip ? '/strip' : '';
1445   - imageUrl += gravity ? '/gravity/' + gravity : '';
1446   - imageUrl += quality ? '/quality/' + quality : '';
1447   - imageUrl += crop ? '/crop/' + crop : '';
1448   - imageUrl += rotate ? '/rotate/' + rotate : '';
1449   - imageUrl += format ? '/format/' + format : '';
1450   - imageUrl += blur ? '/blur/' + blur : '';
1451   -
1452   - if (key) {
1453   - imageUrl = this.getUrl(key) + '?' + imageUrl;
1454   - }
1455   - return imageUrl;
1456   - };
1457   -
1458   - /**
1459   - * invoke the watermark api of Qiniu
1460   - * @param {Object} api params
1461   - * @param {String} key of file
1462   - * @return {String} url of processed image
1463   - */
1464   - this.watermark = function(op, key) {
1465   - var mode = op.mode;
1466   - if (!mode) {
1467   - return false;
1468   - }
1469   -
1470   - var imageUrl = 'watermark/' + mode;
1471   -
1472   - if (mode === 1) {
1473   - var image = op.image || '';
1474   - if (!image) {
1475   - return false;
1476   - }
1477   - imageUrl += image ? '/image/' + this.URLSafeBase64Encode(image) : '';
1478   - } else if (mode === 2) {
1479   - var text = op.text ? op.text : '',
1480   - font = op.font ? op.font : '',
1481   - fontsize = op.fontsize ? op.fontsize : '',
1482   - fill = op.fill ? op.fill : '';
1483   - if (!text) {
1484   - return false;
1485   - }
1486   - imageUrl += text ? '/text/' + this.URLSafeBase64Encode(text) : '';
1487   - imageUrl += font ? '/font/' + this.URLSafeBase64Encode(font) : '';
1488   - imageUrl += fontsize ? '/fontsize/' + fontsize : '';
1489   - imageUrl += fill ? '/fill/' + this.URLSafeBase64Encode(fill) : '';
1490   - } else {
1491   - // Todo mode3
1492   - return false;
1493   - }
1494   -
1495   - var dissolve = op.dissolve || '',
1496   - gravity = op.gravity || '',
1497   - dx = op.dx || '',
1498   - dy = op.dy || '';
1499   -
1500   - imageUrl += dissolve ? '/dissolve/' + dissolve : '';
1501   - imageUrl += gravity ? '/gravity/' + gravity : '';
1502   - imageUrl += dx ? '/dx/' + dx : '';
1503   - imageUrl += dy ? '/dy/' + dy : '';
1504   -
1505   - if (key) {
1506   - imageUrl = this.getUrl(key) + '?' + imageUrl;
1507   - }
1508   - return imageUrl;
1509   - };
1510   -
1511   - /**
1512   - * invoke the imageInfo api of Qiniu
1513   - * @param {String} key of file
1514   - * @return {Object} image info
1515   - */
1516   - this.imageInfo = function(key) {
1517   - if (!key) {
1518   - return false;
1519   - }
1520   - var url = this.getUrl(key) + '?imageInfo';
1521   - var xhr = this.createAjax();
1522   - var info;
1523   - var that = this;
1524   - xhr.open('GET', url, false);
1525   - xhr.onreadystatechange = function() {
1526   - if (xhr.readyState === 4 && xhr.status === 200) {
1527   - info = that.parseJSON(xhr.responseText);
1528   - }
1529   - };
1530   - xhr.send();
1531   - return info;
1532   - };
1533   -
1534   - /**
1535   - * invoke the exif api of Qiniu
1536   - * @param {String} key of file
1537   - * @return {Object} image exif
1538   - */
1539   - this.exif = function(key) {
1540   - if (!key) {
1541   - return false;
1542   - }
1543   - var url = this.getUrl(key) + '?exif';
1544   - var xhr = this.createAjax();
1545   - var info;
1546   - var that = this;
1547   - xhr.open('GET', url, false);
1548   - xhr.onreadystatechange = function() {
1549   - if (xhr.readyState === 4 && xhr.status === 200) {
1550   - info = that.parseJSON(xhr.responseText);
1551   - }
1552   - };
1553   - xhr.send();
1554   - return info;
1555   - };
1556   -
1557   - /**
1558   - * invoke the exif or imageInfo api of Qiniu
1559   - * according with type param
1560   - * @param {String} ['exif'|'imageInfo']type of info
1561   - * @param {String} key of file
1562   - * @return {Object} image exif or info
1563   - */
1564   - this.get = function(type, key) {
1565   - if (!key || !type) {
1566   - return false;
1567   - }
1568   - if (type === 'exif') {
1569   - return this.exif(key);
1570   - } else if (type === 'imageInfo') {
1571   - return this.imageInfo(key);
1572   - }
1573   - return false;
1574   - };
1575   -
1576   - /**
1577   - * invoke api of Qiniu like a pipeline
1578   - * @param {Array of Object} params of a series api call
1579   - * each object in array is options of api which name is set as 'fop' property
1580   - * each api's output will be next api's input
1581   - * @param {String} key of file
1582   - * @return {String|Boolean} url of processed image
1583   - */
1584   - this.pipeline = function(arr, key) {
1585   - var isArray = Object.prototype.toString.call(arr) === '[object Array]';
1586   - var option, errOp, imageUrl = '';
1587   - if (isArray) {
1588   - for (var i = 0, len = arr.length; i < len; i++) {
1589   - option = arr[i];
1590   - if (!option.fop) {
1591   - return false;
1592   - }
1593   - switch (option.fop) {
1594   - case 'watermark':
1595   - imageUrl += this.watermark(option) + '|';
1596   - break;
1597   - case 'imageView2':
1598   - imageUrl += this.imageView2(option) + '|';
1599   - break;
1600   - case 'imageMogr2':
1601   - imageUrl += this.imageMogr2(option) + '|';
1602   - break;
1603   - default:
1604   - errOp = true;
1605   - break;
1606   - }
1607   - if (errOp) {
1608   - return false;
1609   - }
1610   - }
1611   - if (key) {
1612   - imageUrl = this.getUrl(key) + '?' + imageUrl;
1613   - var length = imageUrl.length;
1614   - if (imageUrl.slice(length - 1) === '|') {
1615   - imageUrl = imageUrl.slice(0, length - 1);
1616   - }
1617   - }
1618   - return imageUrl;
1619   - }
1620   - return false;
1621   - };
1622   -}
1623   -
1624   -var Qiniu = new QiniuJsSDK();
1625   -
1626   -global.Qiniu = Qiniu;
1627   -
1628   -global.QiniuJsSDK = QiniuJsSDK;
1629   -
1630   -})( window );
parent/center.manager/src/main/webapp/WEB-INF/static/js/qiniu.min.js View file @ a2758e4
1   -/*! qiniu-js v1.0.19 | Copyright 2015 by Qiniu */
2   -!function(global){function createCookie(a,b,c){var d=new Date;d.setTime(d.getTime()+24*c*60*60*1e3);var e="; expires="+d.toGMTString();document.cookie=a+"="+b+e+"; path=/"}function readCookie(a){var b=a+"=";var c=document.cookie.split(";");for(var d=0,e=c.length;e>d;d++){var f=c[d];while(" "===f.charAt(0))f=f.substring(1,f.length);if(0===f.indexOf(b))return f.substring(b.length,f.length)}return null}window.localStorage||(window.localStorage={setItem:function(a,b){createCookie(a,b,30)},getItem:function(a){return readCookie(a)},removeItem:function(a){createCookie(a,"",-1)}});function QiniuJsSDK(){var that=this;this.detectIEVersion=function(){var a=4,b=document.createElement("div"),c=b.getElementsByTagName("i");while(b.innerHTML="<!--[if gt IE "+a+"]><i></i><![endif]-->",c[0])a++;return a>4?a:!1};var logger={MUTE:0,FATA:1,ERROR:2,WARN:3,INFO:4,DEBUG:5,TRACE:6,level:0};function log(a,b){var c="[qiniu-js-sdk]["+a+"]";var d=c;for(var e=0;e<b.length;e++)d+="string"==typeof b[e]?" "+b[e]:" "+that.stringifyJSON(b[e]);that.detectIEVersion()?console.log(d):(b.unshift(c),console.log.apply(console,b)),document.getElementById("qiniu-js-sdk-log")&&(document.getElementById("qiniu-js-sdk-log").innerHTML+="<p>"+d+"</p>")}function makeLogFunc(a){var b=a.toLowerCase();logger[b]=function(){if(window.console&&window.console.log&&logger.level>=logger[a]){var c=Array.prototype.slice.call(arguments);log(b,c)}}}for(var property in logger)logger.hasOwnProperty(property)&&"number"==typeof logger[property]&&!logger.hasOwnProperty(property.toLowerCase())&&makeLogFunc(property);var qiniuUploadUrl;qiniuUploadUrl="https:"===window.location.protocol?"https://up.qbox.me":"http://upload.qiniu.com";var qiniuUploadUrls=["http://upload.qiniu.com","http://up.qiniu.com"];var qiniuUpHosts={http:["http://upload.qiniu.com","http://up.qiniu.com"],https:["https://up.qbox.me"]};var changeUrlTimes=0;this.resetUploadUrl=function(){var a="https:"===window.location.protocol?qiniuUpHosts.https:qiniuUpHosts.http;var b=changeUrlTimes%a.length;qiniuUploadUrl=a[b],changeUrlTimes++,logger.debug("resetUploadUrl: "+qiniuUploadUrl)},this.isImage=function(a){return a=a.split(/[?#]/)[0],/\.(png|jpg|jpeg|gif|bmp)$/i.test(a)},this.getFileExtension=function(a){var b=a.split(".");var c;return c=1===b.length||""===b[0]&&2===b.length?"":b.pop().toLowerCase()},this.utf8_encode=function(a){if(null===a||"undefined"==typeof a)return"";var b=a+"";var c="",d,e,f=0;d=e=0,f=b.length;for(var g=0;f>g;g++){var h=b.charCodeAt(g);var i=null;if(128>h)e++;else if(h>127&&2048>h)i=String.fromCharCode(h>>6|192,63&h|128);else if(63488&h^!0)i=String.fromCharCode(h>>12|224,h>>6&63|128,63&h|128);else{if(64512&h^!0)throw new RangeError("Unmatched trail surrogate at "+g);var j=b.charCodeAt(++g);if(64512&j^!0)throw new RangeError("Unmatched lead surrogate at "+(g-1));h=((1023&h)<<10)+(1023&j)+65536,i=String.fromCharCode(h>>18|240,h>>12&63|128,h>>6&63|128,63&h|128)}null!==i&&(e>d&&(c+=b.slice(d,e)),c+=i,d=e=g+1)}return e>d&&(c+=b.slice(d,f)),c},this.base64_decode=function(a){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var c,d,e,f,g,h,i,j,k=0,l=0,m="",n=[];if(!a)return a;a+="";do f=b.indexOf(a.charAt(k++)),g=b.indexOf(a.charAt(k++)),h=b.indexOf(a.charAt(k++)),i=b.indexOf(a.charAt(k++)),j=f<<18|g<<12|h<<6|i,c=j>>16&255,d=j>>8&255,e=255&j,64===h?n[l++]=String.fromCharCode(c):64===i?n[l++]=String.fromCharCode(c,d):n[l++]=String.fromCharCode(c,d,e);while(k<a.length);return m=n.join("")},this.base64_encode=function(a){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var c,d,e,f,g,h,i,j,k=0,l=0,m="",n=[];if(!a)return a;a=this.utf8_encode(a+"");do c=a.charCodeAt(k++),d=a.charCodeAt(k++),e=a.charCodeAt(k++),j=c<<16|d<<8|e,f=j>>18&63,g=j>>12&63,h=j>>6&63,i=63&j,n[l++]=b.charAt(f)+b.charAt(g)+b.charAt(h)+b.charAt(i);while(k<a.length);switch(m=n.join(""),a.length%3){case 1:m=m.slice(0,-2)+"==";break;case 2:m=m.slice(0,-1)+"="}return m},this.URLSafeBase64Encode=function(a){return a=this.base64_encode(a),a.replace(/\//g,"_").replace(/\+/g,"-")},this.URLSafeBase64Decode=function(a){return a=a.replace(/_/g,"/").replace(/-/g,"+"),this.base64_decode(a)},this.createAjax=function(a){var b={};return b=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP")},this.parseJSON=function(data){if(window.JSON&&window.JSON.parse)return window.JSON.parse(data);var rx_dangerous=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;var text=String(data);return rx_dangerous.lastIndex=0,rx_dangerous.test(text)&&(text=text.replace(rx_dangerous,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})),eval("("+text+")")},this.stringifyJSON=function(a){if(window.JSON&&window.JSON.stringify)return window.JSON.stringify(a);switch(typeof a){case"string":return'"'+a.replace(/(["\\])/g,"\\$1")+'"';case"array":return"["+a.map(that.stringifyJSON).join(",")+"]";case"object":if(a instanceof Array){var b=[];var c=a.length;for(var d=0;c>d;d++)b.push(that.stringifyJSON(a[d]));return"["+b.join(",")+"]"}if(null===a)return"null";var e=[];for(var f in a)a.hasOwnProperty(f)&&e.push(that.stringifyJSON(f)+":"+that.stringifyJSON(a[f]));return"{"+e.join(",")+"}";case"number":return a;case!1:return a;case"boolean":return a}},this.trim=function(a){return null===a?"":a.replace(/^\s+|\s+$/g,"")},this.uploader=function(a){var b=function(){var b=that.detectIEVersion();var c,d,e;var f="Safari"===mOxie.Env.browser&&mOxie.Env.version<=5&&"Windows"===mOxie.Env.os&&"7"===mOxie.Env.osVersion||"Safari"===mOxie.Env.browser&&"iOS"===mOxie.Env.os&&"7"===mOxie.Env.osVersion;b&&9>b&&a.chunk_size&&a.runtimes.indexOf("flash")>=0?a.chunk_size=0:f?a.chunk_size=0:(c=20,d=4<<c,e=plupload.parseSize(a.chunk_size),e>d&&(a.chunk_size=d))};var c=function(a){var b=[];for(var c=0;c<a.length;c++){var d=a[c];0===d.indexOf("-H")?b.push(d.split(" ")[2]):b.push(d)}return b};var d=function(a){var b=a.split(":");var c=b[0];var d=that.parseJSON(that.URLSafeBase64Decode(b[2]));return d.ak=c,d.scope.indexOf(":")>=0?(d.bucket=d.scope.split(":")[0],d.key=d.scope.split(":")[1]):d.bucket=d.scope,d};var e=function(b){var e=d(b);var f=window.location.protocol+"//uc.qbox.me/v1/query?ak="+e.ak+"&bucket="+e.bucket;logger.debug("putPolicy: ",e),logger.debug("get uphosts from: ",f);var g=that.detectIEVersion();var h;g&&9>=g?(h=new mOxie.XMLHttpRequest,mOxie.Env.swf_url=a.flash_swf_url):h=that.createAjax(),h.open("GET",f,!1);var i=function(){if(logger.debug("ajax.readyState: ",h.readyState),4===h.readyState)if(logger.debug("ajax.status: ",h.status),h.status<400){var a=that.parseJSON(h.responseText);qiniuUpHosts.http=c(a.http.up),qiniuUpHosts.https=c(a.https.up),logger.debug("get new uphosts: ",qiniuUpHosts),that.resetUploadUrl()}else logger.error("get uphosts error: ",h.responseText)};g&&9>=g?h.bind("readystatechange",i):h.onreadystatechange=i,h.send()};var f=function(b){return!that.token||a.uptoken_url&&that.tokenInfo.isExpired()?g(b):that.token};var g=function(b){if(a.uptoken)that.token=a.uptoken;else if(a.uptoken_url){logger.debug("get uptoken from: ",that.uptoken_url);var c=that.createAjax();if(c.open("GET",that.uptoken_url,!1),c.setRequestHeader("If-Modified-Since","0"),c.send(),200===c.status){var d=that.parseJSON(c.responseText);that.token=d.uptoken;var f=that.token.split(":");var g=that.parseJSON(that.URLSafeBase64Decode(f[2]));that.tokenMap||(that.tokenMap={});var h=function(a){return Math.ceil(a.getTime()/1e3)};var i=h(new Date(c.getResponseHeader("date")));var j=h(new Date);that.tokenInfo={serverDelay:j-i,deadline:g.deadline,isExpired:function(){var a=this.deadline-h(new Date)+this.serverDelay;return 600>a}},logger.debug("get new uptoken: ",that.token),logger.debug("get token info: ",that.tokenInfo)}else logger.error("get uptoken error: ",c.responseText)}else a.uptoken_func?(logger.debug("get uptoken from uptoken_func"),that.token=a.uptoken_func(b),logger.debug("get new uptoken: ",that.token)):logger.error("one of [uptoken, uptoken_url, uptoken_func] settings in options is required!");return that.token&&e(that.token),that.token};var h=function(b,c,d){var e="",f=!1;if(!a.save_key)if(f=b.getOption&&b.getOption("unique_names"),f=f||b.settings&&b.settings.unique_names){var g=that.getFileExtension(c.name);e=g?c.id+"."+g:c.id}else e="function"==typeof d?d(b,c):c.name;return e};if(a.log_level&&(logger.level=a.log_level),!a.domain)throw"domain setting in options is required!";if(!a.browse_button)throw"browse_button setting in options is required!";if(!a.uptoken&&!a.uptoken_url&&!a.uptoken_func)throw"one of [uptoken, uptoken_url, uptoken_func] settings in options is required!";logger.debug("init uploader start"),logger.debug("environment: ",mOxie.Env),logger.debug("userAgent: ",navigator.userAgent);var i={};var j=a.init&&a.init.Error;var k=a.init&&a.init.FileUploaded;a.init.Error=function(){},a.init.FileUploaded=function(){},that.uptoken_url=a.uptoken_url,that.token="",that.key_handler="function"==typeof a.init.Key?a.init.Key:"",this.domain=a.domain;var l="";var m={isResumeUpload:!1,resumeFilesize:0,startTime:"",currentTime:""};b(),logger.debug("invoke reset_chunk_size()"),logger.debug("op.chunk_size: ",a.chunk_size);var n={url:qiniuUploadUrl,multipart_params:{token:""}};var o=that.detectIEVersion();o&&9>=o&&(n.multipart_params.accept="text/plain; charset=utf-8",logger.debug("add accept text/plain in multipart params")),plupload.extend(i,a,n),logger.debug("option: ",i);var p=new plupload.Uploader(i);logger.debug("new plupload.Uploader(option)"),p.bind("Init",function(b,c){logger.debug("Init event activated"),a.get_new_uptoken||g(null)}),logger.debug("bind Init event"),p.bind("FilesAdded",function(a,b){logger.debug("FilesAdded event activated");var c=a.getOption&&a.getOption("auto_start");c=c||a.settings&&a.settings.auto_start,logger.debug("auto_start: ",c),logger.debug("files: ",b);var d=function(){return"ios"===mOxie.Env.OS.toLowerCase()?!0:!1};if(d())for(var e=0;e<b.length;e++){var f=b[e];var g=that.getFileExtension(f.name);f.name=f.id+"."+g}c&&setTimeout(function(){a.start(),logger.debug("invoke up.start()")},0),a.refresh()}),logger.debug("bind FilesAdded event"),p.bind("BeforeUpload",function(b,c){logger.debug("BeforeUpload event activated"),c.speed=c.speed||0,l="",a.get_new_uptoken&&g(c);var d=function(b,c,d){m.startTime=(new Date).getTime();var f;f=a.save_key?{token:that.token}:{key:h(b,c,d),token:that.token};var g=that.detectIEVersion();g&&9>=g&&(f.accept="text/plain; charset=utf-8",logger.debug("add accept text/plain in multipart params")),logger.debug("directUpload multipart_params_obj: ",f);var i=a.x_vars;if(void 0!==i&&"object"==typeof i)for(var j in i)i.hasOwnProperty(j)&&("function"==typeof i[j]?f["x:"+j]=i[j](b,c):"object"!=typeof i[j]&&(f["x:"+j]=i[j]));b.setOption({url:qiniuUploadUrl,multipart:!0,chunk_size:e()?a.max_file_size:void 0,multipart_params:f})};var e=function(){var a=navigator.userAgent.toLowerCase();return(a.match(/MicroMessenger/i)||"QQBrowser"===mOxie.Env.browser||a.match(/V1_AND_SQ/i))&&"android"===mOxie.Env.OS.toLowerCase()?!0:!1};var i=b.getOption&&b.getOption("chunk_size");if(i=i||b.settings&&b.settings.chunk_size,logger.debug("uploader.runtime: ",p.runtime),logger.debug("chunk_size: ",i),"html5"!==p.runtime&&"flash"!==p.runtime||!i)logger.debug("directUpload because uploader.runtime !== 'html5' || uploader.runtime !== 'flash' || !chunk_size"),d(b,c,that.key_handler);else if(c.size<i||e())logger.debug("directUpload because file.size < chunk_size || is_android_weixin_or_qq()"),d(b,c,that.key_handler);else{var j=localStorage.getItem(c.name);var k=i;if(j){j=that.parseJSON(j);var n=(new Date).getTime();var o=j.time||0;var q=864e5;q>n-o&&100!==j.percent&&c.size===j.total?(c.percent=j.percent,c.loaded=j.offset,l=j.ctx,m.isResumeUpload=!0,m.resumeFilesize=j.offset,j.offset+k>c.size&&(k=c.size-j.offset)):localStorage.removeItem(c.name)}m.startTime=(new Date).getTime();var r={};var s=that.detectIEVersion();s&&9>=s&&(r.accept="text/plain; charset=utf-8",logger.debug("add accept text/plain in multipart params")),b.setOption({url:qiniuUploadUrl+"/mkblk/"+k,multipart:!1,chunk_size:i,required_features:"chunks",headers:{Authorization:"UpToken "+f(c)},multipart_params:r})}}),logger.debug("bind BeforeUpload event"),p.bind("UploadProgress",function(a,b){logger.trace("UploadProgress event activated"),m.currentTime=(new Date).getTime();var c=m.currentTime-m.startTime;var d=b.loaded||0;m.isResumeUpload&&(d=b.loaded-m.resumeFilesize),b.speed=(d/c*1e3).toFixed(0)||0}),logger.debug("bind UploadProgress event"),p.bind("ChunkUploaded",function(a,b,c){logger.debug("ChunkUploaded event activated"),logger.debug("file: ",b),logger.debug("info: ",c);var d=that.parseJSON(c.response);logger.debug("res: ",d),l=l?l+","+d.ctx:d.ctx;var e=c.total-c.offset;var g=a.getOption&&a.getOption("chunk_size");g=g||a.settings&&a.settings.chunk_size,g>e&&(a.setOption({url:qiniuUploadUrl+"/mkblk/"+e}),logger.debug("up.setOption url: ",qiniuUploadUrl+"/mkblk/"+e)),a.setOption({headers:{Authorization:"UpToken "+f(b)}}),localStorage.setItem(b.name,that.stringifyJSON({ctx:l,percent:b.percent,total:c.total,offset:c.offset,time:(new Date).getTime()}))}),logger.debug("bind ChunkUploaded event");var q=qiniuUploadUrls.length;var r=function(a){return q-->0?(setTimeout(function(){that.resetUploadUrl(),a.status=plupload.QUEUED,p.stop(),p.start()},0),!0):(q=qiniuUploadUrls.length,!1)};return p.bind("Error",function(a){return function(b,c){logger.error("Error event activated"),logger.error("err: ",c);var d="";var e=c.file;if(e){switch(c.code){case plupload.FAILED:d="\u4e0a\u4f20\u5931\u8d25\u3002\u8bf7\u7a0d\u540e\u518d\u8bd5\u3002";break;case plupload.FILE_SIZE_ERROR:var f=b.getOption&&b.getOption("max_file_size");f=f||b.settings&&b.settings.max_file_size,d="\u6d4f\u89c8\u5668\u6700\u5927\u53ef\u4e0a\u4f20"+f+"\u3002\u66f4\u5927\u6587\u4ef6\u8bf7\u4f7f\u7528\u547d\u4ee4\u884c\u5de5\u5177\u3002";break;case plupload.FILE_EXTENSION_ERROR:d="\u6587\u4ef6\u9a8c\u8bc1\u5931\u8d25\u3002\u8bf7\u7a0d\u540e\u91cd\u8bd5\u3002";break;case plupload.HTTP_ERROR:if(""===c.response){if(d=c.message||"\u672a\u77e5\u7f51\u7edc\u9519\u8bef\u3002",!r(e))return;break}var g=that.parseJSON(c.response);var h=g.error;switch(c.status){case 400:d="\u8bf7\u6c42\u62a5\u6587\u683c\u5f0f\u9519\u8bef\u3002";break;case 401:d="\u5ba2\u6237\u7aef\u8ba4\u8bc1\u6388\u6743\u5931\u8d25\u3002\u8bf7\u91cd\u8bd5\u6216\u63d0\u4ea4\u53cd\u9988\u3002";break;case 405:d="\u5ba2\u6237\u7aef\u8bf7\u6c42\u9519\u8bef\u3002\u8bf7\u91cd\u8bd5\u6216\u63d0\u4ea4\u53cd\u9988\u3002";break;case 579:d="\u8d44\u6e90\u4e0a\u4f20\u6210\u529f\uff0c\u4f46\u56de\u8c03\u5931\u8d25\u3002";break;case 599:if(d="\u7f51\u7edc\u8fde\u63a5\u5f02\u5e38\u3002\u8bf7\u91cd\u8bd5\u6216\u63d0\u4ea4\u53cd\u9988\u3002",!r(e))return;break;case 614:d="\u6587\u4ef6\u5df2\u5b58\u5728\u3002";try{g=that.parseJSON(g.error),h=g.error||"file exists"}catch(i){h=g.error||"file exists"}break;case 631:d="\u6307\u5b9a\u7a7a\u95f4\u4e0d\u5b58\u5728\u3002";break;case 701:d="\u4e0a\u4f20\u6570\u636e\u5757\u6821\u9a8c\u51fa\u9519\u3002\u8bf7\u91cd\u8bd5\u6216\u63d0\u4ea4\u53cd\u9988\u3002";break;default:if(d="\u672a\u77e5\u9519\u8bef\u3002",!r(e))return}d=d+"("+c.status+"\uff1a"+h+")";break;case plupload.SECURITY_ERROR:d="\u5b89\u5168\u914d\u7f6e\u9519\u8bef\u3002\u8bf7\u8054\u7cfb\u7f51\u7ad9\u7ba1\u7406\u5458\u3002";break;case plupload.GENERIC_ERROR:d="\u4e0a\u4f20\u5931\u8d25\u3002\u8bf7\u7a0d\u540e\u518d\u8bd5\u3002";break;case plupload.IO_ERROR:d="\u4e0a\u4f20\u5931\u8d25\u3002\u8bf7\u7a0d\u540e\u518d\u8bd5\u3002";break;case plupload.INIT_ERROR:d="\u7f51\u7ad9\u914d\u7f6e\u9519\u8bef\u3002\u8bf7\u8054\u7cfb\u7f51\u7ad9\u7ba1\u7406\u5458\u3002",p.destroy();break;default:if(d=c.message+c.details,!r(e))return}a&&a(b,c,d)}b.refresh()}}(j)),logger.debug("bind Error event"),p.bind("FileUploaded",function(b){return function(c,d,e){logger.debug("FileUploaded event activated"),logger.debug("file: ",d),logger.debug("info: ",e);var f=function(c,d,e){if(a.downtoken_url){var f=that.createAjax();f.open("POST",a.downtoken_url,!0),f.setRequestHeader("Content-type","application/x-www-form-urlencoded"),f.onreadystatechange=function(){if(4===f.readyState)if(200===f.status){var a;try{a=that.parseJSON(f.responseText)}catch(g){throw"invalid json format"}var h={};plupload.extend(h,that.parseJSON(e),a),b&&b(c,d,that.stringifyJSON(h))}else p.trigger("Error",{status:f.status,response:f.responseText,file:d,code:plupload.HTTP_ERROR})},f.send("key="+that.parseJSON(e).key+"&domain="+a.domain)}else b&&b(c,d,e)};var g=that.parseJSON(e.response);if(l=l?l:g.ctx,logger.debug("ctx: ",l),l){var i="";logger.debug("save_key: ",a.save_key),a.save_key||(i=h(c,d,that.key_handler),i=i?"/key/"+that.URLSafeBase64Encode(i):"");var j="/fname/"+that.URLSafeBase64Encode(d.name);logger.debug("op.x_vars: ",a.x_vars);var k=a.x_vars,m="",n="";if(void 0!==k&&"object"==typeof k)for(var o in k)k.hasOwnProperty(o)&&("function"==typeof k[o]?m=that.URLSafeBase64Encode(k[o](c,d)):"object"!=typeof k[o]&&(m=that.URLSafeBase64Encode(k[o])),n+="/x:"+o+"/"+m);var q=qiniuUploadUrl+"/mkfile/"+d.size+i+j+n;var r=that.detectIEVersion();var s;r&&9>=r?(s=new mOxie.XMLHttpRequest,mOxie.Env.swf_url=a.flash_swf_url):s=that.createAjax(),s.open("POST",q,!0),s.setRequestHeader("Content-Type","text/plain;charset=UTF-8"),s.setRequestHeader("Authorization","UpToken "+that.token);var t=function(){if(logger.debug("ajax.readyState: ",s.readyState),4===s.readyState){localStorage.removeItem(d.name);var a;200===s.status?(a=s.responseText,logger.debug("mkfile is success: ",a),f(c,d,a)):(a={status:s.status,response:s.responseText,file:d,code:-200,responseHeaders:s.getAllResponseHeaders()},logger.debug("mkfile is error: ",a),p.trigger("Error",a))}};r&&9>=r?s.bind("readystatechange",t):s.onreadystatechange=t,s.send(l),logger.debug("mkfile: ",q)}else f(c,d,e.response)}}(k)),logger.debug("bind FileUploaded event"),p.init(),logger.debug("invoke uploader.init()"),logger.debug("init uploader end"),p},this.getUrl=function(a){if(!a)return!1;a=encodeURI(a);var b=this.domain;return"/"!==b.slice(b.length-1)&&(b+="/"),b+a},this.imageView2=function(a,b){if(!/^\d$/.test(a.mode))return!1;var c=a.mode,d=a.w||"",e=a.h||"",f=a.q||"",g=a.format||"";if(!d&&!e)return!1;var h="imageView2/"+c;return h+=d?"/w/"+d:"",h+=e?"/h/"+e:"",h+=f?"/q/"+f:"",h+=g?"/format/"+g:"",b&&(h=this.getUrl(b)+"?"+h),h},this.imageMogr2=function(a,b){var c=a["auto-orient"]||"",d=a.thumbnail||"",e=a.strip||"",f=a.gravity||"",g=a.crop||"",h=a.quality||"",i=a.rotate||"",j=a.format||"",k=a.blur||"";var l="imageMogr2";return l+=c?"/auto-orient":"",l+=d?"/thumbnail/"+d:"",l+=e?"/strip":"",l+=f?"/gravity/"+f:"",l+=h?"/quality/"+h:"",l+=g?"/crop/"+g:"",l+=i?"/rotate/"+i:"",l+=j?"/format/"+j:"",l+=k?"/blur/"+k:"",b&&(l=this.getUrl(b)+"?"+l),l},this.watermark=function(a,b){var c=a.mode;if(!c)return!1;var d="watermark/"+c;if(1===c){var e=a.image||"";if(!e)return!1;d+=e?"/image/"+this.URLSafeBase64Encode(e):""}else{if(2!==c)return!1;var f=a.text?a.text:"",g=a.font?a.font:"",h=a.fontsize?a.fontsize:"",i=a.fill?a.fill:"";if(!f)return!1;d+=f?"/text/"+this.URLSafeBase64Encode(f):"",d+=g?"/font/"+this.URLSafeBase64Encode(g):"",d+=h?"/fontsize/"+h:"",d+=i?"/fill/"+this.URLSafeBase64Encode(i):""}var j=a.dissolve||"",k=a.gravity||"",l=a.dx||"",m=a.dy||"";return d+=j?"/dissolve/"+j:"",d+=k?"/gravity/"+k:"",d+=l?"/dx/"+l:"",d+=m?"/dy/"+m:"",b&&(d=this.getUrl(b)+"?"+d),d},this.imageInfo=function(a){if(!a)return!1;var b=this.getUrl(a)+"?imageInfo";var c=this.createAjax();var d;var e=this;return c.open("GET",b,!1),c.onreadystatechange=function(){4===c.readyState&&200===c.status&&(d=e.parseJSON(c.responseText))},c.send(),d},this.exif=function(a){if(!a)return!1;var b=this.getUrl(a)+"?exif";var c=this.createAjax();var d;var e=this;return c.open("GET",b,!1),c.onreadystatechange=function(){4===c.readyState&&200===c.status&&(d=e.parseJSON(c.responseText))},c.send(),d},this.get=function(a,b){return b&&a?"exif"===a?this.exif(b):"imageInfo"===a?this.imageInfo(b):!1:!1},this.pipeline=function(a,b){var c="[object Array]"===Object.prototype.toString.call(a);var d,e,f="";if(c){for(var g=0,h=a.length;h>g;g++){if(d=a[g],!d.fop)return!1;switch(d.fop){case"watermark":f+=this.watermark(d)+"|";break;case"imageView2":f+=this.imageView2(d)+"|";break;case"imageMogr2":f+=this.imageMogr2(d)+"|";break;default:e=!0}if(e)return!1}if(b){f=this.getUrl(b)+"?"+f;var i=f.length;"|"===f.slice(i-1)&&(f=f.slice(0,i-1))}return f}return!1}}var Qiniu=new QiniuJsSDK;global.Qiniu=Qiniu,global.QiniuJsSDK=QiniuJsSDK}(window);
3   -//# sourceMappingURL=dist/qiniu.min.map
parent/center.manager/src/main/webapp/WEB-INF/views/articles/articles_edit.html View file @ a2758e4
... ... @@ -6,16 +6,9 @@
6 6 }
7 7 </style>
8 8  
9   -<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/ueditor.config.js"></script>
10   -<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/ueditor.all.min.js"></script>
11   -<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/lang/zh-cn/zh-cn.js"></script>
12   -<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/moxie.js"></script>
13   -<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/plupload.dev.js"></script>
14   -<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/i18n/zh_CN.js"></script>
15   -<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/qiniu.min.js"></script>
16   -<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/qiniu.js"></script>
17 9  
18 10  
  11 +
19 12 <div class="ibox float-e-margins">
20 13 <div class="ibox-content">
21 14 <div class="col-sm-12">
22 15  
23 16  
24 17  
... ... @@ -62,22 +55,22 @@
62 55 <div class="form-group">
63 56 <label class="col-sm-2 control-label" for="">*封面:</label>
64 57 <div class="col-sm-5">
65   - <div class="btn-group m-b">
66   - <label class="btn btn-sm btn-info w-sm"
  58 + <div class="btn-group m-b col-sm-12 ">
  59 + <label class="btn btn-sm btn-info w-sm col-sm-3"
67 60 onclick="switchContent(1)"> <i
68 61 class="fa fa-check text-active" id="commonCon"></i> 普通内容
69   - </label> <label class="btn btn-sm btn-success w-sm"
  62 + </label> <label class="btn btn-sm btn-success w-sm col-sm-3"
70 63 onclick="switchContent(2)"> <i class="fa text-active"
71 64 id="specialCon"></i> 专题内容
72 65 </label>
73 66 </div>
74   - <div class="col-sm-12 no-padder">
  67 + <div class="col-sm-12 no-padder" id="container">
75 68 <div data-multiple="false"
76 69 title="点击上传" id="pickfiles"
77 70 class="btn btn-primary btn-upload m-b-sm">
78 71 <i class="fa fa-cloud-upload text"></i> 点击上传图片
79 72 </div>
80   - <img class="b wrapper-xs w img-responsive" style="width: 200px"
  73 + <img class="b wrapper-xs w img-responsive" style="width: 200px" id="pickImage"
81 74 src="${ctx}/static/images/p0.jpg" />
82 75 </div>
83 76 </div>
84 77  
85 78  
86 79  
87 80  
... ... @@ -90,23 +83,21 @@
90 83 class="form-control w-lg" required="" aria-required="true">
91 84 </div>
92 85 </div>
93   - <div class="form-group">
  86 + <div class="form-group" id="linkContent">
94 87 <label class="col-sm-2 control-label">*链接:</label>
95 88 <div class="col-sm-5">
96 89 <input type="text" type="url" name="link"
97   - class="form-control w-lg" required="" aria-required="true">
  90 + class="form-control w-lg" aria-required="true">
98 91 </div>
99 92 </div>
100   - <div class="form-group">
  93 + <div class="form-group" id="zaiyaoContent">
101 94 <label class="col-sm-2 control-label">*摘要:</label>
102 95 <div class="col-sm-5">
103   - <input type="text" ng-maxlength="255" name="introduction"
104   - ng-model="article.introduction" class="form-control w-lg"
105   - ng-required="radioModel.imageType == 'Ordinary'">
  96 + <input type="text" maxlength="255" name="introduction" class="form-control w-lg">
106 97 </div>
107 98 </div>
108 99  
109   - <div class="form-group" id="imageContext">
  100 + <div class="form-group" id="zhengwenConent">
110 101 <label class="col-sm-2 control-label">正文:</label>
111 102 <div class="col-sm-5">
112 103 <script id="editor" name="richText" type="text/plain"></script>
113 104  
114 105  
115 106  
116 107  
117 108  
118 109  
119 110  
120 111  
121 112  
122 113  
123 114  
124 115  
125 116  
... ... @@ -131,54 +122,73 @@
131 122 </div>
132 123 #end #extends("/common/base_list.html")
133 124  
134   -<script type="text/javascript">
135   - $('#multChe').on('ifClicked', function(event) {
136   - $("#imageTitle").toggleClass("hidden");
137   - $("#imageContext").toggleClass("hidden");
138   - $("#imageTitle").toggleClass("show");
139   - $("#imageContext").toggleClass("show");
140   - });
  125 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/ueditor.config.js"></script>
  126 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/ueditor.all.min.js"></script>
  127 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/lang/zh-cn/zh-cn.js"></script>
  128 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/js/moxie.js"></script>
  129 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/js/plupload.dev.js"></script>
  130 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/js/i18n/zh_CN.js"></script>
  131 +<script type="text/javascript" src="${ctx}/static/js/plugins/qiniu/qiniu.min.js"></script>
141 132  
  133 +<script type="text/javascript">
  134 +
142 135 function switchContent(num) {
143   - if (num == 1) {
  136 + if (num == 1) {//普通内容
144 137 $("#commonCon").addClass("fa-check");
145 138 $("#specialCon").removeClass("fa-check");
  139 +
  140 + $("#zaiyaoContent").show();
  141 + $("#zhengwenConent").show();
  142 + $("#linkContent").hide();
  143 +
  144 +
146 145 } else {
147 146 $("#commonCon").removeClass("fa-check");
148 147 $("#specialCon").addClass("fa-check");
  148 +
  149 + $("#zaiyaoContent").hide();
  150 + $("#zhengwenConent").hide();
  151 + $("#linkContent").show();
149 152 }
150 153 }
151 154  
152 155 function initUpload(){
153   -
154 156 var uploader = Qiniu.uploader({
155 157 runtimes: 'html5,flash,html4', //上传模式,依次退化
156 158 browse_button: 'pickfiles', //上传选择的点选按钮,**必需**
157   - uptoken_url: '/token', //Ajax请求upToken的Url,**强烈建议设置**(服务端提供)
  159 + uptoken_url: "${ctx}/ueditor/uploadGetToken", //Ajax请求upToken的Url,**强烈建议设置**(服务端提供)
  160 + //uptoken:"hZgfmtYjqtz1UC96gy4uatu5FmyvtoPULkUB9QgA:J51SWS11RoS_0JhE_4LaU_YAWj4=:eyJzY29wZSI6Im1vbW15YmFieSIsImRlYWRsaW5lIjoxNDkzMDA2ODY3fQ==",
158 161 // uptoken : '<Your upload token>', //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
159   - // unique_names: true, // 默认 false,key为文件名。若开启该选项,SDK为自动生成上传成功后的key(文件名)。
  162 + unique_names: true, // 默认 false,key为文件名。若开启该选项,SDK为自动生成上传成功后的key(文件名)。
160 163 // save_key: true, // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`,则开启,SDK会忽略对key的处理
161   - domain: 'http://qiniu-plupload.qiniudn.com/', //bucket 域名,下载资源时用到,**必需**
  164 + domain: 'http://img1.healthbaby.com.cn/', //bucket 域名,下载资源时用到,**必需**
162 165 get_new_uptoken: false, //设置上传文件的时候是否每次都重新获取新的token
163 166 container: 'container', //上传区域DOM ID,默认是browser_button的父元素,
164 167 max_file_size: '100mb', //最大文件体积限制
165   - flash_swf_url: 'js/plupload/Moxie.swf', //引入flash,相对路径
  168 + flash_swf_url: '${ctx}/js/plugins/plupload/Moxie.swf', //引入flash,相对路径
166 169 max_retries: 3, //上传失败最大重试次数
167   - dragdrop: true, //开启可拖曳上传
168   - drop_element: 'container', //拖曳上传区域元素的ID,拖曳文件或文件夹后可触发上传
  170 + dragdrop: false, //开启可拖曳上传
169 171 chunk_size: '4mb', //分块上传时,每片的体积
170 172 auto_start: true, //选择文件后自动上传,若关闭需要自己绑定事件触发上传
171 173 init: {
172 174 'FilesAdded': function(up, files) {
173 175 plupload.each(files, function(file) {
174   - // 文件添加进队列后,处理相关的事情
  176 + // var progress = new FileProgress(file, 'fsUploadProgress');
  177 + // progress.setStatus("等待...");
  178 + // progress.bindUploadCancel(up);
175 179 });
176 180 },
177 181 'BeforeUpload': function(up, file) {
178   - // 每个文件上传前,处理相关的事情
  182 + // var progress = new FileProgress(file, 'fsUploadProgress');
  183 + // var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  184 + // if (up.runtime === 'html5' && chunk_size) {
  185 + // progress.setChunkProgess(chunk_size);
  186 + // }
179 187 },
180 188 'UploadProgress': function(up, file) {
181   - // 每个文件上传时,处理相关的事情
  189 + // var progress = new FileProgress(file, 'fsUploadProgress');
  190 + // var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  191 + // progress.setProgress(file.percent + "%", file.speed, chunk_size);
182 192 },
183 193 'FileUploaded': function(up, file, info) {
184 194 // 每个文件上传成功后,处理相关的事情
... ... @@ -189,9 +199,16 @@
189 199 // }
190 200 // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
191 201  
192   - // var domain = up.getOption('domain');
193   - // var res = parseJSON(info);
194   - // var sourceLink = domain + res.key; 获取上传成功后的文件的Url
  202 + //var progress = new FileProgress(err.file, 'fsUploadProgress');
  203 + // progress.setError();
  204 + // progress.setStatus(errTip);
  205 +
  206 + var domain = up.getOption('domain');
  207 +
  208 + var res = JSON.parse(info);
  209 + var sourceLink = domain + res.key; //获取上传成功后的文件的Url+
  210 +
  211 + $("#pickImage").attr("src",sourceLink);
195 212 },
196 213 'Error': function(up, err, errTip) {
197 214 //上传出错时,处理相关的事情
... ... @@ -216,7 +233,7 @@
216 233 initialFrameHeight : 200,
217 234 initialFrameWidth : "100%"
218 235 });
219   - $.getJSON("${ctx}/contentCategories/list", function(data) {
  236 + $.getJSON("${ctx}/contentCategories/selelist", function(data) {
220 237 if (data.success) {
221 238 var columnList = "<option value=''>请选择</option>";
222 239 data.data.forEach(function(d, i) {
... ... @@ -227,7 +244,7 @@
227 244 }
228 245 });
229 246  
230   - $.get("${ctx}/contentTags/list", "json", function(data) {
  247 + $.get("${ctx}/contentTags/seleList", "json", function(data) {
231 248 if (data.success) {
232 249 var seleHtml = "";
233 250 data.data.forEach(function(d, i) {
234 251  
235 252  
... ... @@ -260,12 +277,16 @@
260 277 });
261 278  
262 279 function save() {
263   - var content = UE.getEditor('editor').getContent();
  280 +
264 281 if ($('#validForm').valid()) {
265 282 var data = $('#validForm').serialize();
  283 + var pickImgSrc = $("#pickImage").attr("src");
  284 + var content = UE.getEditor('editor').getContent();
  285 + data+="&content="+content;
  286 + data+="&image="+pickImgSrc;
266 287 //data+"&"
267   - ajaxPost(APP.PATH + "/contentMessageTemplate/create", data);
268   - parent.reloadGrid('dataTable');
  288 + //ajaxPost(APP.PATH + "/contentMessageTemplate/create", data);
  289 + //parent.reloadGrid('dataTable');
269 290 }
270 291 }
271 292 </script>
parent/center.manager/src/main/webapp/WEB-INF/views/articles/articles_list.html View file @ a2758e4
  1 +#override("body")
  2 +<div class="row wrapper border-bottom white-bg page-heading">
  3 + <div class="col-sm-10">
  4 + <div style="padding-top:30px;">
  5 + <form role="form" class="form-inline">
  6 + <div class="form-group">
  7 + <input type="text" placeholder="请输入栏目名称" id="nameSearch" class="form-control">
  8 + </div>
  9 + </form>
  10 + </div>
  11 + </div>
  12 + <div class="col-sm-2">
  13 + <div class="title-action" onclick="search();">
  14 + <a class="btn btn-primary"><i class="fa fa-search"></i> 查询</a>
  15 + </div>
  16 + </div>
  17 +</div>
  18 +<div class="wrapper wrapper-content">
  19 + <div class="row">
  20 + <div class="col-sm-12">
  21 + <div id="toolbar">
  22 + <button class="btn btn-info " type="button" onclick="add();"><i class="fa fa-plus"></i> 新增</button>
  23 + <button class="btn btn-info " type="button" onclick="edit();"><i class="fa fa-paste"></i> 编辑</button>
  24 + <!--
  25 + <button class="btn btn-info " type="button" onclick="del();"><i class="fa fa-trash"></i> 删除</button>
  26 + -->
  27 + </div>
  28 + <table id="dataTable"></table>
  29 + </div>
  30 + </div>
  31 +</div>
  32 +#end
  33 +#override("js")
  34 +<script type="text/javascript">
  35 +function search(){
  36 + var queryParams = {
  37 + query:{
  38 + name: $("#nameSearch").val()
  39 + }
  40 + }
  41 + $('#dataTable').bootstrapTable('refresh', queryParams );
  42 +}
  43 +var controllerRequestMappint = "/contentArticles/";
  44 +
  45 +function edit(){
  46 + var id = getSingleSelectedValue("dataTable","id");
  47 + if(id){
  48 + fullWindow("修改标签", APP.PATH + controllerRequestMappint + id + "/toEdit");
  49 + }
  50 +}
  51 +
  52 +function del(){
  53 + goDelete("dataTable","id", APP.PATH + controllerRequestMappint + "@value@/delete");
  54 +}
  55 +var default_dataUrl = APP.PATH + controllerRequestMappint + "list";
  56 +var default_dataColumns = [{
  57 + field: 'perent',
  58 + title: '',
  59 + checkbox: true
  60 + },{
  61 + field: 'title',
  62 + title: '标题'
  63 + },{
  64 + field: 'categoryName',
  65 + title: '所属栏目'
  66 + },{
  67 + field: 'typeName',
  68 + title: '分类'
  69 + },{
  70 + field:"tagsName",
  71 + title:"标签"
  72 + },{
  73 + field:"createName",
  74 + title:"添加人"
  75 + }];
  76 +
  77 +</script>
  78 +#end
  79 +#extends("/common/base_list.html")
parent/center.manager/src/main/webapp/WEB-INF/views/categories/categonies_edit.html View file @ a2758e4
  1 +#override("css") #end #override("body")
  2 +<style>
  3 +#select6 {
  4 + width: 100%;
  5 + height: 36px;
  6 +}
  7 +</style>
  8 +
  9 +
  10 +
  11 +
  12 +<div class="ibox float-e-margins">
  13 + <div class="ibox-content">
  14 + <div class="col-sm-12">
  15 + <form id="validForm" class="form-horizontal m-t"
  16 + novalidate="novalidate">
  17 + <div class="form-group">
  18 + <label class="col-sm-2 control-label">父栏目名称:</label>
  19 + <div class="col-sm-5">
  20 + <input type="text" class="form-control" disabled class="form-control"
  21 + placeholder="无" name="">
  22 + </div>
  23 + </div>
  24 + <div class="form-group">
  25 + <label class="col-sm-2 control-label">*栏目名称:</label>
  26 + <div class="col-sm-5">
  27 + <input type="text" class="form-control" class="form-control"
  28 + placeholder="请填入栏目名称" name="">
  29 + </div>
  30 + </div>
  31 + <div class="form-group">
  32 + <label class="col-sm-2 control-label" for="">*栏目icon:</label>
  33 + <div class="col-sm-5">
  34 + <div class="col-sm-12 no-padder" id="container">
  35 + <div data-multiple="false"
  36 + title="点击上传" id="pickfiles"
  37 + class="btn btn-primary btn-upload m-b-sm">
  38 + <i class="fa fa-cloud-upload text"></i> 点击上传图片
  39 + </div>
  40 + <img class="b wrapper-xs w img-responsive" style="width: 200px" id="pickImage"
  41 + src="${ctx}/static/images/p0.jpg" />
  42 + </div>
  43 + </div>
  44 + </div>
  45 +
  46 +
  47 +
  48 + <div class="form-group" id="zhengwenConent">
  49 + <label class="col-sm-2 control-label">栏目简介:</label>
  50 + <div class="col-sm-5">
  51 + <script id="editor" name="richText" type="text/plain"></script>
  52 + </div>
  53 + </div>
  54 +
  55 + <div class="hr-line-dashed"></div>
  56 + <div class="form-group">
  57 + <div class="col-sm-7 col-sm-offset-3 pull-right">
  58 + <button type="button" class="btn btn-primary" onclick="save();">
  59 + <i class="fa fa-check"></i>&nbsp;提交
  60 + </button>
  61 + <button type="button" class="btn btn-white"
  62 + onclick="parent.closeAll();">
  63 + <i class="fa fa-close"></i>&nbsp;取消
  64 + </button>
  65 + </div>
  66 + </div>
  67 + </form>
  68 + </div>
  69 + </div>
  70 +</div>
  71 +#end #extends("/common/base_list.html")
  72 +
  73 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/ueditor.config.js"></script>
  74 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/ueditor.all.min.js"></script>
  75 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/lang/zh-cn/zh-cn.js"></script>
  76 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/js/moxie.js"></script>
  77 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/js/plupload.dev.js"></script>
  78 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/js/i18n/zh_CN.js"></script>
  79 +<script type="text/javascript" src="${ctx}/static/js/plugins/qiniu/qiniu.min.js"></script>
  80 +
  81 +<script type="text/javascript">
  82 +
  83 + function switchContent(num) {
  84 + if (num == 1) {//普通内容
  85 + $("#commonCon").addClass("fa-check");
  86 + $("#specialCon").removeClass("fa-check");
  87 +
  88 + $("#zaiyaoContent").show();
  89 + $("#zhengwenConent").show();
  90 + $("#linkContent").hide();
  91 +
  92 +
  93 + } else {
  94 + $("#commonCon").removeClass("fa-check");
  95 + $("#specialCon").addClass("fa-check");
  96 +
  97 + $("#zaiyaoContent").hide();
  98 + $("#zhengwenConent").hide();
  99 + $("#linkContent").show();
  100 + }
  101 + }
  102 +
  103 + function initUpload(){
  104 + var uploader = Qiniu.uploader({
  105 + runtimes: 'html5,flash,html4', //上传模式,依次退化
  106 + browse_button: 'pickfiles', //上传选择的点选按钮,**必需**
  107 + uptoken_url: "${ctx}/ueditor/uploadGetToken", //Ajax请求upToken的Url,**强烈建议设置**(服务端提供)
  108 + //uptoken:"hZgfmtYjqtz1UC96gy4uatu5FmyvtoPULkUB9QgA:J51SWS11RoS_0JhE_4LaU_YAWj4=:eyJzY29wZSI6Im1vbW15YmFieSIsImRlYWRsaW5lIjoxNDkzMDA2ODY3fQ==",
  109 + // uptoken : '<Your upload token>', //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
  110 + unique_names: true, // 默认 false,key为文件名。若开启该选项,SDK为自动生成上传成功后的key(文件名)。
  111 + // save_key: true, // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`,则开启,SDK会忽略对key的处理
  112 + domain: 'http://img1.healthbaby.com.cn/', //bucket 域名,下载资源时用到,**必需**
  113 + get_new_uptoken: false, //设置上传文件的时候是否每次都重新获取新的token
  114 + container: 'container', //上传区域DOM ID,默认是browser_button的父元素,
  115 + max_file_size: '100mb', //最大文件体积限制
  116 + flash_swf_url: '${ctx}/js/plugins/plupload/Moxie.swf', //引入flash,相对路径
  117 + max_retries: 3, //上传失败最大重试次数
  118 + dragdrop: false, //开启可拖曳上传
  119 + chunk_size: '4mb', //分块上传时,每片的体积
  120 + auto_start: true, //选择文件后自动上传,若关闭需要自己绑定事件触发上传
  121 + init: {
  122 + 'FilesAdded': function(up, files) {
  123 + plupload.each(files, function(file) {
  124 + // var progress = new FileProgress(file, 'fsUploadProgress');
  125 + // progress.setStatus("等待...");
  126 + // progress.bindUploadCancel(up);
  127 + });
  128 + },
  129 + 'BeforeUpload': function(up, file) {
  130 + // var progress = new FileProgress(file, 'fsUploadProgress');
  131 + // var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  132 + // if (up.runtime === 'html5' && chunk_size) {
  133 + // progress.setChunkProgess(chunk_size);
  134 + // }
  135 + },
  136 + 'UploadProgress': function(up, file) {
  137 + // var progress = new FileProgress(file, 'fsUploadProgress');
  138 + // var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  139 + // progress.setProgress(file.percent + "%", file.speed, chunk_size);
  140 + },
  141 + 'FileUploaded': function(up, file, info) {
  142 + // 每个文件上传成功后,处理相关的事情
  143 + // 其中 info 是文件上传成功后,服务端返回的json,形式如
  144 + // {
  145 + // "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
  146 + // "key": "gogopher.jpg"
  147 + // }
  148 + // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
  149 +
  150 + //var progress = new FileProgress(err.file, 'fsUploadProgress');
  151 + // progress.setError();
  152 + // progress.setStatus(errTip);
  153 +
  154 + var domain = up.getOption('domain');
  155 +
  156 + var res = JSON.parse(info);
  157 + var sourceLink = domain + res.key; //获取上传成功后的文件的Url+
  158 +
  159 + $("#pickImage").attr("src",sourceLink);
  160 + },
  161 + 'Error': function(up, err, errTip) {
  162 + //上传出错时,处理相关的事情
  163 + },
  164 + 'UploadComplete': function() {
  165 + //队列文件处理完毕后,处理相关的事情
  166 + },
  167 + 'Key': function(up, file) {
  168 + var key = "";
  169 + return key
  170 + }
  171 + }
  172 + });
  173 +
  174 + }
  175 +
  176 + $(function() {
  177 + //初始化图片上传插件
  178 + initUpload();
  179 + //初始化
  180 + var ue = UE.getEditor('editor', {
  181 + initialFrameHeight : 200,
  182 + initialFrameWidth : "100%"
  183 + });
  184 + $.getJSON("${ctx}/contentCategories/list", function(data) {
  185 + if (data.success) {
  186 + var columnList = "<option value=''>请选择</option>";
  187 + data.data.forEach(function(d, i) {
  188 + columnList += "<option value='"+d.id+"'>" + d.name + "</option>";
  189 + });
  190 + $("#columnList").empty();
  191 + $("#columnList").append(columnList);
  192 + }
  193 + });
  194 +
  195 + $.get("${ctx}/contentTags/list", "json", function(data) {
  196 + if (data.success) {
  197 + var seleHtml = "";
  198 + data.data.forEach(function(d, i) {
  199 + seleHtml += '<option value="'+d.id+'">' + d.tagName + '</option>';
  200 + });
  201 +
  202 + $("#select6").empty();
  203 + $("#select6").append(seleHtml);
  204 +
  205 + $('#select6').selectator({
  206 + prefix : 'selectator_', // CSS class prefix
  207 + height : 'auto', // auto or element
  208 + useDimmer : false, // dims the screen when option list is visible
  209 + useSearch : true, // if false, the search boxes are removed and
  210 + // `showAllOptionsOnFocus` is forced to true
  211 + keepOpen : true, // if true, then the dropdown will not close when
  212 + // selecting options, but stay open until losing focus
  213 + showAllOptionsOnFocus : true, // shows all options if input box is empty
  214 + selectFirstOptionOnSearch : true, // selects the topmost option on every search
  215 + searchCallback : function(value) {
  216 + }, // Callback function when enter is pressed and
  217 + // no option is active in multi select box
  218 + labels : {
  219 + search : 'Search...' // Placeholder text in search box in single select box
  220 + }
  221 + });
  222 +
  223 + }
  224 + });
  225 + });
  226 +
  227 + function save() {
  228 +
  229 + if ($('#validForm').valid()) {
  230 + var data = $('#validForm').serialize();
  231 + var pickImgSrc = $("#pickImage").attr("src");
  232 + var content = UE.getEditor('editor').getContent();
  233 + data+="&content="+content;
  234 + data+="&image="+pickImgSrc;
  235 + //data+"&"
  236 + //ajaxPost(APP.PATH + "/contentMessageTemplate/create", data);
  237 + //parent.reloadGrid('dataTable');
  238 + }
  239 + }
  240 +</script>
parent/center.manager/src/main/webapp/WEB-INF/views/categories/categonies_list.html View file @ a2758e4
  1 +#override("body")
  2 +<div class="row wrapper border-bottom white-bg page-heading">
  3 + <div class="col-sm-10">
  4 + <div style="padding-top:30px;">
  5 + <form role="form" class="form-inline">
  6 + <div class="form-group">
  7 + <input type="text" placeholder="请输入栏目名称" id="nameSearch" class="form-control">
  8 + </div>
  9 + </form>
  10 + </div>
  11 + </div>
  12 + <div class="col-sm-2">
  13 + <div class="title-action" onclick="search();">
  14 + <a class="btn btn-primary"><i class="fa fa-search"></i> 查询</a>
  15 + </div>
  16 + </div>
  17 +</div>
  18 +<div class="wrapper wrapper-content">
  19 + <div class="row">
  20 + <div class="col-sm-12">
  21 + <div id="toolbar">
  22 + <button class="btn btn-info " type="button" onclick="add();"><i class="fa fa-plus"></i> 新增</button>
  23 + <button class="btn btn-info " type="button" onclick="edit();"><i class="fa fa-paste"></i> 编辑</button>
  24 + <!--
  25 + <button class="btn btn-info " type="button" onclick="del();"><i class="fa fa-trash"></i> 删除</button>
  26 + -->
  27 + </div>
  28 + <table id="dataTable"></table>
  29 + </div>
  30 + </div>
  31 +</div>
  32 +#end
  33 +#override("js")
  34 +<script type="text/javascript">
  35 +function search(){
  36 + var queryParams = {
  37 + query:{
  38 + name: $("#nameSearch").val()
  39 + }
  40 + }
  41 + $('#dataTable').bootstrapTable('refresh', queryParams );
  42 +}
  43 +var controllerRequestMappint = "/contentCategories/";
  44 +
  45 +function add() {
  46 + fullWindow("新增栏目", APP.PATH + controllerRequestMappint + "/toEdit");
  47 +}
  48 +
  49 +function edit(){
  50 + var id = getSingleSelectedValue("dataTable","id");
  51 + if(id){
  52 + fullWindow("修改栏目", APP.PATH + controllerRequestMappint + id + "/toEdit");
  53 + }
  54 +}
  55 +
  56 +function del(){
  57 + goDelete("dataTable","id", APP.PATH + controllerRequestMappint + "@value@/delete");
  58 +}
  59 +var default_dataUrl = APP.PATH + controllerRequestMappint + "list";
  60 +var default_dataColumns = [{
  61 + field: 'perent',
  62 + title: '',
  63 + formatter:function(value,row,index){
  64 + if(value == ""){
  65 + return '无';
  66 + }else {
  67 + return '下一级'
  68 + }
  69 + }
  70 + },{
  71 + field: 'name',
  72 + title: '栏目名称'
  73 + },{
  74 + field: 'description',
  75 + title: '栏目简介'
  76 + },{
  77 + field: 'level',
  78 + title: '栏目等级'
  79 + }];
  80 +
  81 +</script>
  82 +#end
  83 +#extends("/common/base_list.html")
parent/center.manager/src/main/webapp/WEB-INF/views/content/template_edit.html View file @ a2758e4
... ... @@ -83,7 +83,7 @@
83 83 //初始化
84 84 var ue = UE.getEditor('editor',{initialFrameHeight:200,initialFrameWidth:"100%" });
85 85  
86   - $.get("${ctx}/contentTags/list","json",function(data){
  86 + $.get("${ctx}/contentTags/seleList","json",function(data){
87 87 if(data.success){
88 88 var seleHtml = "";
89 89 data.data.forEach(function(d,i){
parent/center.manager/src/main/webapp/WEB-INF/views/tags/tags_edit.html View file @ a2758e4
  1 +#override("css") #end #override("body")
  2 +<style>
  3 +#select6 {
  4 + width: 100%;
  5 + height: 36px;
  6 +}
  7 +</style>
  8 +
  9 +
  10 +
  11 +
  12 +<div class="ibox float-e-margins">
  13 + <div class="ibox-content">
  14 + <div class="col-sm-12">
  15 + <form id="validForm" class="form-horizontal m-t"
  16 + novalidate="novalidate">
  17 + <div class="form-group">
  18 + <label class="col-sm-4 control-label">父标签名称:</label>
  19 + <div class="col-sm-3">
  20 + <input type="text" class="form-control" disabled class="form-control"
  21 + placeholder="无" name="">
  22 + </div>
  23 + </div>
  24 + <div class="hr-line-dashed"></div>
  25 + <div class="form-group">
  26 + <label class="col-sm-4 control-label">*标签名称:</label>
  27 + <div class="col-sm-3">
  28 + <input type="text" class="form-control" class="form-control"
  29 + placeholder="请填入标签名称" name="">
  30 + </div>
  31 + </div>
  32 + <div class="hr-line-dashed"></div>
  33 + <div class="form-group">
  34 + <label class="col-sm-4 control-label">*标签简介:</label>
  35 + <div class="col-sm-3">
  36 + <textarea class="form-control" rows="4" cols="12" aria-required="true" name="content" required="true" placeholder="请输入短信内容"></textarea>
  37 + </div>
  38 + </div>
  39 +
  40 + <div class="hr-line-dashed"></div>
  41 + <div class="form-group">
  42 + <div class="col-sm-7 col-sm-offset-3 pull-right">
  43 + <button type="button" class="btn btn-primary" onclick="save();">
  44 + <i class="fa fa-check"></i>&nbsp;提交
  45 + </button>
  46 + <button type="button" class="btn btn-white"
  47 + onclick="parent.closeAll();">
  48 + <i class="fa fa-close"></i>&nbsp;取消
  49 + </button>
  50 + </div>
  51 + </div>
  52 + </form>
  53 + </div>
  54 + </div>
  55 +</div>
  56 +#end #extends("/common/base_list.html")
  57 +
  58 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/ueditor.config.js"></script>
  59 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/ueditor.all.min.js"></script>
  60 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/ueditor/lang/zh-cn/zh-cn.js"></script>
  61 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/js/moxie.js"></script>
  62 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/js/plupload.dev.js"></script>
  63 +<script type="text/javascript" charset="utf-8" src="${ctx}/static/js/plugins/plupload/js/i18n/zh_CN.js"></script>
  64 +<script type="text/javascript" src="${ctx}/static/js/plugins/qiniu/qiniu.min.js"></script>
  65 +
  66 +<script type="text/javascript">
  67 +
  68 + function switchContent(num) {
  69 + if (num == 1) {//普通内容
  70 + $("#commonCon").addClass("fa-check");
  71 + $("#specialCon").removeClass("fa-check");
  72 +
  73 + $("#zaiyaoContent").show();
  74 + $("#zhengwenConent").show();
  75 + $("#linkContent").hide();
  76 +
  77 +
  78 + } else {
  79 + $("#commonCon").removeClass("fa-check");
  80 + $("#specialCon").addClass("fa-check");
  81 +
  82 + $("#zaiyaoContent").hide();
  83 + $("#zhengwenConent").hide();
  84 + $("#linkContent").show();
  85 + }
  86 + }
  87 +
  88 + function initUpload(){
  89 + var uploader = Qiniu.uploader({
  90 + runtimes: 'html5,flash,html4', //上传模式,依次退化
  91 + browse_button: 'pickfiles', //上传选择的点选按钮,**必需**
  92 + uptoken_url: "${ctx}/ueditor/uploadGetToken", //Ajax请求upToken的Url,**强烈建议设置**(服务端提供)
  93 + //uptoken:"hZgfmtYjqtz1UC96gy4uatu5FmyvtoPULkUB9QgA:J51SWS11RoS_0JhE_4LaU_YAWj4=:eyJzY29wZSI6Im1vbW15YmFieSIsImRlYWRsaW5lIjoxNDkzMDA2ODY3fQ==",
  94 + // uptoken : '<Your upload token>', //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
  95 + unique_names: true, // 默认 false,key为文件名。若开启该选项,SDK为自动生成上传成功后的key(文件名)。
  96 + // save_key: true, // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`,则开启,SDK会忽略对key的处理
  97 + domain: 'http://img1.healthbaby.com.cn/', //bucket 域名,下载资源时用到,**必需**
  98 + get_new_uptoken: false, //设置上传文件的时候是否每次都重新获取新的token
  99 + container: 'container', //上传区域DOM ID,默认是browser_button的父元素,
  100 + max_file_size: '100mb', //最大文件体积限制
  101 + flash_swf_url: '${ctx}/js/plugins/plupload/Moxie.swf', //引入flash,相对路径
  102 + max_retries: 3, //上传失败最大重试次数
  103 + dragdrop: false, //开启可拖曳上传
  104 + chunk_size: '4mb', //分块上传时,每片的体积
  105 + auto_start: true, //选择文件后自动上传,若关闭需要自己绑定事件触发上传
  106 + init: {
  107 + 'FilesAdded': function(up, files) {
  108 + plupload.each(files, function(file) {
  109 + // var progress = new FileProgress(file, 'fsUploadProgress');
  110 + // progress.setStatus("等待...");
  111 + // progress.bindUploadCancel(up);
  112 + });
  113 + },
  114 + 'BeforeUpload': function(up, file) {
  115 + // var progress = new FileProgress(file, 'fsUploadProgress');
  116 + // var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  117 + // if (up.runtime === 'html5' && chunk_size) {
  118 + // progress.setChunkProgess(chunk_size);
  119 + // }
  120 + },
  121 + 'UploadProgress': function(up, file) {
  122 + // var progress = new FileProgress(file, 'fsUploadProgress');
  123 + // var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
  124 + // progress.setProgress(file.percent + "%", file.speed, chunk_size);
  125 + },
  126 + 'FileUploaded': function(up, file, info) {
  127 + // 每个文件上传成功后,处理相关的事情
  128 + // 其中 info 是文件上传成功后,服务端返回的json,形式如
  129 + // {
  130 + // "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
  131 + // "key": "gogopher.jpg"
  132 + // }
  133 + // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
  134 +
  135 + //var progress = new FileProgress(err.file, 'fsUploadProgress');
  136 + // progress.setError();
  137 + // progress.setStatus(errTip);
  138 +
  139 + var domain = up.getOption('domain');
  140 +
  141 + var res = JSON.parse(info);
  142 + var sourceLink = domain + res.key; //获取上传成功后的文件的Url+
  143 +
  144 + $("#pickImage").attr("src",sourceLink);
  145 + },
  146 + 'Error': function(up, err, errTip) {
  147 + //上传出错时,处理相关的事情
  148 + },
  149 + 'UploadComplete': function() {
  150 + //队列文件处理完毕后,处理相关的事情
  151 + },
  152 + 'Key': function(up, file) {
  153 + var key = "";
  154 + return key
  155 + }
  156 + }
  157 + });
  158 +
  159 + }
  160 +
  161 + $(function() {
  162 + //初始化图片上传插件
  163 + initUpload();
  164 + //初始化
  165 + var ue = UE.getEditor('editor', {
  166 + initialFrameHeight : 200,
  167 + initialFrameWidth : "100%"
  168 + });
  169 + $.getJSON("${ctx}/contentCategories/selelist", function(data) {
  170 + if (data.success) {
  171 + var columnList = "<option value=''>请选择</option>";
  172 + data.data.forEach(function(d, i) {
  173 + columnList += "<option value='"+d.id+"'>" + d.name + "</option>";
  174 + });
  175 + $("#columnList").empty();
  176 + $("#columnList").append(columnList);
  177 + }
  178 + });
  179 +
  180 + $.get("${ctx}/contentTags/list", "json", function(data) {
  181 + if (data.success) {
  182 + var seleHtml = "";
  183 + data.data.forEach(function(d, i) {
  184 + seleHtml += '<option value="'+d.id+'">' + d.tagName + '</option>';
  185 + });
  186 +
  187 + $("#select6").empty();
  188 + $("#select6").append(seleHtml);
  189 +
  190 + $('#select6').selectator({
  191 + prefix : 'selectator_', // CSS class prefix
  192 + height : 'auto', // auto or element
  193 + useDimmer : false, // dims the screen when option list is visible
  194 + useSearch : true, // if false, the search boxes are removed and
  195 + // `showAllOptionsOnFocus` is forced to true
  196 + keepOpen : true, // if true, then the dropdown will not close when
  197 + // selecting options, but stay open until losing focus
  198 + showAllOptionsOnFocus : true, // shows all options if input box is empty
  199 + selectFirstOptionOnSearch : true, // selects the topmost option on every search
  200 + searchCallback : function(value) {
  201 + }, // Callback function when enter is pressed and
  202 + // no option is active in multi select box
  203 + labels : {
  204 + search : 'Search...' // Placeholder text in search box in single select box
  205 + }
  206 + });
  207 +
  208 + }
  209 + });
  210 + });
  211 +
  212 + function save() {
  213 +
  214 + if ($('#validForm').valid()) {
  215 + var data = $('#validForm').serialize();
  216 + var pickImgSrc = $("#pickImage").attr("src");
  217 + var content = UE.getEditor('editor').getContent();
  218 + data+="&content="+content;
  219 + data+="&image="+pickImgSrc;
  220 + //data+"&"
  221 + //ajaxPost(APP.PATH + "/contentMessageTemplate/create", data);
  222 + //parent.reloadGrid('dataTable');
  223 + }
  224 + }
  225 +</script>
parent/center.manager/src/main/webapp/WEB-INF/views/tags/tags_list.html View file @ a2758e4
  1 +#override("body")
  2 +<div class="row wrapper border-bottom white-bg page-heading">
  3 + <div class="col-sm-10">
  4 + <div style="padding-top:30px;">
  5 + <form role="form" class="form-inline">
  6 + <div class="form-group">
  7 + <input type="text" placeholder="请输入栏目名称" id="nameSearch" class="form-control">
  8 + </div>
  9 + </form>
  10 + </div>
  11 + </div>
  12 + <div class="col-sm-2">
  13 + <div class="title-action" onclick="search();">
  14 + <a class="btn btn-primary"><i class="fa fa-search"></i> 查询</a>
  15 + </div>
  16 + </div>
  17 +</div>
  18 +<div class="wrapper wrapper-content">
  19 + <div class="row">
  20 + <div class="col-sm-12">
  21 + <div id="toolbar">
  22 + <button class="btn btn-info " type="button" onclick="add();"><i class="fa fa-plus"></i> 新增</button>
  23 + <button class="btn btn-info " type="button" onclick="edit();"><i class="fa fa-paste"></i> 编辑</button>
  24 + <!--
  25 + <button class="btn btn-info " type="button" onclick="del();"><i class="fa fa-trash"></i> 删除</button>
  26 + -->
  27 + </div>
  28 + <table id="dataTable"></table>
  29 + </div>
  30 + </div>
  31 +</div>
  32 +#end
  33 +#override("js")
  34 +<script type="text/javascript">
  35 +function search(){
  36 + var queryParams = {
  37 + query:{
  38 + name: $("#nameSearch").val()
  39 + }
  40 + }
  41 + $('#dataTable').bootstrapTable('refresh', queryParams );
  42 +}
  43 +var controllerRequestMappint = "/contentTags/";
  44 +
  45 +function add() {
  46 + fullWindow("新增标签", APP.PATH + controllerRequestMappint + "/toEdit");
  47 +}
  48 +
  49 +function edit(){
  50 + var id = getSingleSelectedValue("dataTable","id");
  51 + if(id){
  52 + fullWindow("修改标签", APP.PATH + controllerRequestMappint + id + "/toEdit");
  53 + }
  54 +}
  55 +
  56 +function del(){
  57 + goDelete("dataTable","id", APP.PATH + controllerRequestMappint + "@value@/delete");
  58 +}
  59 +var default_dataUrl = APP.PATH + controllerRequestMappint + "list";
  60 +var default_dataColumns = [{
  61 + field: 'perent',
  62 + title: '',
  63 + formatter:function(value,row,index){
  64 + if(value == ""){
  65 + return '无';
  66 + }else {
  67 + return '下一级'
  68 + }
  69 + }
  70 + },{
  71 + field: 'tagName',
  72 + title: '栏目名称'
  73 + },{
  74 + field: 'tagDesc',
  75 + title: '栏目简介'
  76 + },{
  77 + field: 'level',
  78 + title: '栏目等级'
  79 + }];
  80 +
  81 +</script>
  82 +#end
  83 +#extends("/common/base_list.html")