阿里云服务器免费领卷啦。

捡代码论坛-最全的游戏源码下载技术网站!

 找回密码
 立 即 注 册

QQ登录

只需一步,快速开始

搜索
关于源码区的附件失效或欺骗帖, 处理办法
查看: 2299|回复: 0

js实现ctrl+v上传图片-源码下载

[复制链接]

4208

主题

210

回帖

12万

积分

管理员

管理员

Rank: 9Rank: 9Rank: 9

积分
126189
QQ
发表于 2016-8-24 21:58:06 | 显示全部楼层 |阅读模式
js实现ctrl+v上传图片

描述:实现类似QQ截图删上传图片的功能
a、需要的js插件
  1. paste.image.js
  2. 地址:https://github.com/iyangyuan/pasteimg
复制代码
b、paste.image.js
  1. (function($,exports){
  2.   $.fn.extend({
  3.     pasteImage: function(callback){
  4.       var util = {
  5.         /*
  6.         *  @function:
  7.         *    从指定类继承,并且带简单数据构造器
  8.         *  @params:
  9.         *    parent 0个构造参数的父类,默认Object
  10.         *  @return:
  11.         *    子类,可以访问父类的prototype属性
  12.         */
  13.         extend: function(parent){
  14.           /*
  15.           *  @example:
  16.           *    if the param construct={name: "nadel"};
  17.           *    then the function construct will like:
  18.           *    function(name){
  19.           *      this.name = name;
  20.           *    }
  21.           */
  22.           parent = parent || Object;
  23.           var fn = function(construct){
  24.             var attribute = "";
  25.             for(attribute in construct){
  26.               if(Object.prototype.hasOwnProperty.call(construct, attribute)){
  27.                 this[attribute] = construct[attribute];
  28.               }
  29.             }
  30.           };
  31.           fn.prototype = new parent();
  32.           strategys.push(fn);
  33.            
  34.           return fn;
  35.         },
  36.         /*
  37.         *  @function:
  38.         *    遍历数组中的object,根据正则匹配指定属性
  39.         *  @params:
  40.         *    array object数组
  41.         *    property object属性
  42.         *    regex object属性值正则表达式
  43.         *  @return:
  44.         *    匹配到的object数组
  45.         */
  46.         getProperty: function(array, property, regex){
  47.           var result = [],
  48.               i = 0;
  49.           for(i = 0; i<array.length; i++){
  50.             if(regex.test(array[i][property])){
  51.               result.push(array[i]);
  52.             }
  53.           }
  54.           return result;
  55.         },
  56.         /*
  57.         *  @function:
  58.         *    将image document对象转换为DataUrl
  59.         *  @params:
  60.         *    element: image document对象,可以用document.getElementById获取
  61.         *    type: 生成的图片类型,例如:image/png,默认为image/png
  62.         *  @return:
  63.         *    DataUrl
  64.         */
  65.         imageToDataUrl: function(element, type){
  66.           type = type || "image/png";
  67.           try{
  68.             //利用canvas获取图片的DataUrl,但受跨域限制
  69.             var canvas = document.createElement('canvas'),
  70.                 ctx = canvas.getContext('2d'),
  71.                 result = "";
  72.             canvas.width = element.width;
  73.             canvas.height = element.height;
  74.             ctx.drawImage(element, 0, 0);
  75.             result = canvas.toDataURL(type);
  76.             if(result === "data:,"){
  77.               result = "";
  78.             }
  79.             
  80.             return result;
  81.           }catch(e){
  82.             //目标服务器不允许跨域访问资源
  83.             return "";
  84.           }
  85.         },
  86.         /*
  87.         *  @functions:
  88.         *    将一个类数组中的数据push到真正的数组中
  89.         *  @params:
  90.         *    array 数组
  91.         *    arrayLike 类数组
  92.         */
  93.         arrayLikePush: function(array, arrayLike){
  94.           var i = 0;
  95.           for(i = 0;i<arrayLike.length;i++){
  96.             array.push(arrayLike[i]);
  97.           }
  98.         }
  99.       },
  100.       strategys = [],
  101.       strategy = {},
  102.       i = 0;
  103.       
  104.       //算法类(接口)
  105.       var Strategy = function(){};
  106.       Strategy.prototype.exec = function(){
  107.         //意在必须重写
  108.         throw new Error("The method 'chrome' must be override!");
  109.       };
  110.       Strategy.prototype.isSuport = function(){
  111.         throw new Error("The method 'chrome' must be override!");
  112.       };
  113.       
  114.       //谷歌浏览器算法
  115.       var Chrome = util.extend(Strategy);
  116.       Chrome.prototype.exec = function(){
  117.         var that = this;
  118.         that.$element.on("paste",function(event){
  119.           var items = (event.clipboardData || event.originalEvent.clipboardData).items,
  120.               //取出html对象
  121.               htmlBlobs = util.getProperty(items, "type", /^text\/html$/im),
  122.               imgElements = [],
  123.               loadedCount = 0,
  124.               htmlImages = [],
  125.               htmlResults = [],
  126.               reader = {},
  127.               parseFinish = function(){
  128.                 var $html = {},
  129.                     $imageLoadDiv = {};
  130.                  
  131.                 if(htmlResults.length === htmlBlobs.length){
  132.                   //解析html中的图片
  133.                   for(k = 0;k<htmlResults.length;k++){
  134.                     $html = htmlResults[k].replace(/\n|\r|\n\r/g, "");
  135.                     $html = $html.replace("<html><body>", "<div>");
  136.                     $html = $html.replace("</body></html>", "</div>");
  137.                     $html = $($html);
  138.                     util.arrayLikePush(imgElements, $html.find("img"));
  139.                   }
  140.                   //图片预加载
  141.                   $("body").append(imageLoadDiv);
  142.                   $imageLoadDiv = $("#paste_image_load");
  143.                   for(k = 0; k<imgElements.length; k++){
  144.                     imgElements[k].onload = imgOnload;
  145.                     $imageLoadDiv.append(imgElements[k]);
  146.                   }
  147.                 }
  148.               },
  149.               loadFinish = function(){
  150.                 var dataurl = "",
  151.                     k = 0;
  152.                 if(imgElements.length === loadedCount){
  153.                   //尝试将图像dom转换成dataurl,如果失败,返回img src
  154.                   for(k = 0;k<imgElements.length;k++){
  155.                     dataurl = "";
  156.                     dataurl = util.imageToDataUrl(imgElements[k]);
  157.                     if(dataurl){
  158.                       htmlImages.push(dataurl);
  159.                     }else{
  160.                       htmlImages.push(imgElements[k].getAttribute("src"));
  161.                     }
  162.                   }
  163.                   
  164.                   $("#paste_image_load").remove();
  165.                   
  166.                   //返回结果
  167.                   that.callback(htmlImages);
  168.                 }
  169.               },
  170.               imgOnload = function(){
  171.                 loadedCount = loadedCount+1;
  172.                 loadFinish();
  173.               },
  174.               imageLoadDiv = "<div id='paste_image_load' style='height: 0;width: 0;display: none;'></div>",
  175.               i = 0;
  176.            
  177.           //提取html对象中的图片
  178.           for(i = 0;i<htmlBlobs.length;i++){
  179.             htmlBlobs[i].getAsString(function(html){
  180.               htmlResults.push(html);
  181.               parseFinish();
  182.             });
  183.           }
  184.         });
  185.       };
  186.       Chrome.prototype.isSuport = function(){
  187.         return window.navigator.userAgent.toLowerCase().indexOf("chrome")>-1;
  188.       };
  189.       
  190.       //火狐浏览器和IE11浏览器算法
  191.       var FirefoxAndIE11 = util.extend(Strategy);
  192.       FirefoxAndIE11.prototype.exec = function(){
  193.         var that = this,
  194.             clipboardDiv = "<div id='paste_content_catch' contentEditable='true' style='position: fixed;left: -9999px;top: -9999px; opacity: 0;'></div>",
  195.             $clipboardDiv = {},
  196.             i = 0;
  197.          
  198.         //初始化clipboard catch
  199.         $("body").append(clipboardDiv);
  200.         $clipboardDiv = $("#paste_content_catch");
  201.         //监听ctrl+v事件
  202.         that.$element.on("keydown",function(event){
  203.           if(event.ctrlKey == 1 && event.keyCode == 86){
  204.             $clipboardDiv.html("");
  205.             $clipboardDiv.focus();
  206.             //模拟多线程
  207.             setTimeout(function(){
  208.               var id = "paste_image_load_" + new Date().getTime(),
  209.                   imageLoadDiv = "<div id='"+id+"' style='height: 0;width: 0;display: none;'></div>",
  210.                   $imageLoadDiv = {},
  211.                   imageElements = [],
  212.                   images = [],
  213.                   loadedCount = 0;
  214.                
  215.               //获取剪切板中的img元素
  216.               imageElements = $clipboardDiv.find("img");
  217.               //图片预加载
  218.               $("body").append(imageLoadDiv);
  219.               $imageLoadDiv = $("#"+id);
  220.               for(i = 0;i<imageElements.length;i++){
  221.                 imageElements[i].onload = function(){
  222.                   var dataurl = "",
  223.                       k = 0;
  224.                   
  225.                   loadedCount = loadedCount+1;
  226.                   if(imageElements.length === loadedCount){
  227.                     //尝试将图像dom转换成dataurl,如果失败,返回img src
  228.                     for(k = 0;k<imageElements.length;k++){
  229.                       dataurl = "";
  230.                       dataurl = util.imageToDataUrl(imageElements[k]);
  231.                       if(dataurl){
  232.                         images.push(dataurl);
  233.                       }else{
  234.                         images.push(imageElements[k].getAttribute("src"));
  235.                       }
  236.                     }
  237.                      
  238.                     $imageLoadDiv.remove();
  239.                      
  240.                     //返回结果
  241.                     that.callback(images);
  242.                   }
  243.                 };
  244.                 $imageLoadDiv.append(imageElements[i]);
  245.               }
  246.               imageElements = $imageLoadDiv.find("img");
  247.               $clipboardDiv.html("");
  248.               that.$element.focus();
  249.             },0);
  250.           }
  251.         });
  252.       };
  253.       FirefoxAndIE11.prototype.isSuport = function(){
  254.         var result = false;
  255.          
  256.         try{
  257.           result = window.navigator.userAgent.toLowerCase().indexOf("firefox")>-1 ||
  258.                    (Object.hasOwnProperty.call(window, "ActiveXObject") && !window.ActiveXObject);
  259.         }catch(e){}
  260.          
  261.         return result;
  262.       };
  263.       
  264.       //选择策略
  265.       for(i = 0;i<strategys.length;i++){
  266.         strategy = new strategys[i]({
  267.           $element: $(this),
  268.           callback: callback
  269.         });
  270.          
  271.         if(strategy.isSuport()){
  272.           strategy.exec();
  273.           break;
  274.         }
  275.       }
  276.     }
  277.   });
  278. })(jQuery,this);
复制代码

c、demo.html
  1. <body>
  2.     <input type="text" id="container" placeholder="在这粘贴图片"/>
  3.     <script>
  4.       $("#container").pasteImage(function(imgs){
  5.         $.each(imgs,function(i,n){
  6.         var  imageData= n.replace("data:image/png;base64,", "");
  7.         var imageUrl=""
  8.         $.ajax({
  9.              type: "POST",
  10.              url: path+"/tmsSellMsg/uploadImageByBase64Code",
  11.              data: {"imageData":imageData},
  12.              dataType: "json",
  13.              async:false,
  14.              success: function(data){
  15.                          imageUrl = data;
  16.                 }
  17.             });
  18.            $("body").append("<img src='"+imageUrl+"' >");
  19.         });
  20.       });
  21.     </script>
  22. </body>
复制代码
d、springmvc
  1. @RequestMapping(value = "/uploadImageByBase64Code", method = RequestMethod.POST)
  2. public @ResponseBody String insertTmsSellMsgByExcel2(String imageData) throws Exception {
  3.     byte[] buf = Base64Utils.decodeFromString(imageData);
  4.     InputStream sbs = new ByteArrayInputStream(buf);
  5.     String imageUrl= OSSUtils.putObject(sbs);
  6.     return JsonUtils.objectToJson(imageUrl);
  7. }
复制代码

致此结束……
http://www.cnblogs.com/huanchupkblog/p/5795626.html


捡代码论坛-最全的游戏源码下载技术网站! - 论坛版权郑重声明:
1、本主题所有言论和图片纯属会员个人意见,与本论坛立场无关
2、本站所有主题由该帖子作者发表,该帖子作者与捡代码论坛-最全的游戏源码下载技术网站!享有帖子相关版权
3、捡代码论坛版权,详细了解请点击。
4、本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,不存在任何商业目的与商业用途。
5、若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。 我们不承担任何技术及版权问题,且不对任何资源负法律责任。
6、如无法链接失效或侵犯版权,请给我们来信:jiandaima@foxmail.com

回复

使用道具 举报

*滑块验证:
您需要登录后才可以回帖 登录 | 立 即 注 册

本版积分规则

技术支持
在线咨询
QQ咨询
3351529868

QQ|手机版|小黑屋|捡代码论坛-专业源码分享下载 ( 陕ICP备15015195号-1|网站地图

GMT+8, 2024-4-27 15:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表