描述:實現類似QQ截圖刪上傳圖片的功能
a、需要的js插件
paste.image.js 地址:https://github.com/iyangyuan/pasteimg
b、paste.image.js
(function($,exports){ $.fn.extend({ pasteImage: function(callback){ var util = { /* * @function: * 從指定類繼承,並且帶簡單數據構造器 * @params: * parent 0個構造參數的父類,默認Object * @return: * 子類,可以訪問父類的prototype屬性 */ extend: function(parent){ /* * @example: * if the param construct={name: "nadel"}; * then the function construct will like: * function(name){ * this.name = name; * } */ parent = parent || Object; var fn = function(construct){ var attribute = ""; for(attribute in construct){ if(Object.prototype.hasOwnProperty.call(construct, attribute)){ this[attribute] = construct[attribute]; } } }; fn.prototype = new parent(); strategys.push(fn); return fn; }, /* * @function: * 遍歷數組中的object,根據正則匹配指定屬性 * @params: * array object數組 * property object屬性 * regex object屬性值正則表達式 * @return: * 匹配到的object數組 */ getProperty: function(array, property, regex){ var result = [], i = 0; for(i = 0; i<array.length; i++){ if(regex.test(array[i][property])){ result.push(array[i]); } } return result; }, /* * @function: * 將image document對象轉換為DataUrl * @params: * element: image document對象,可以用document.getElementById獲取 * type: 生成的圖片類型,例如:image/png,默認為image/png * @return: * DataUrl */ imageToDataUrl: function(element, type){ type = type || "image/png"; try{ //利用canvas獲取圖片的DataUrl,但受跨域限制 var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), result = ""; canvas.width = element.width; canvas.height = element.height; ctx.drawImage(element, 0, 0); result = canvas.toDataURL(type); if(result === "data:,"){ result = ""; } return result; }catch(e){ //目標服務器不允許跨域訪問資源 return ""; } }, /* * @functions: * 將一個類數組中的數據push到真正的數組中 * @params: * array 數組 * arrayLike 類數組 */ arrayLikePush: function(array, arrayLike){ var i = 0; for(i = 0;i<arrayLike.length;i++){ array.push(arrayLike[i]); } } }, strategys = [], strategy = {}, i = 0; //算法類(接口) var Strategy = function(){}; Strategy.prototype.exec = function(){ //意在必須重寫 throw new Error("The method 'chrome' must be override!"); }; Strategy.prototype.isSuport = function(){ throw new Error("The method 'chrome' must be override!"); }; //谷歌瀏覽器算法 var Chrome = util.extend(Strategy); Chrome.prototype.exec = function(){ var that = this; that.$element.on("paste",function(event){ var items = (event.clipboardData || event.originalEvent.clipboardData).items, //取出html對象 htmlBlobs = util.getProperty(items, "type", /^text\/html$/im), imgElements = [], loadedCount = 0, htmlImages = [], htmlResults = [], reader = {}, parseFinish = function(){ var $html = {}, $imageLoadDiv = {}; if(htmlResults.length === htmlBlobs.length){ //解析html中的圖片 for(k = 0;k<htmlResults.length;k++){ $html = htmlResults[k].replace(/\n|\r|\n\r/g, ""); $html = $html.replace("<html><body>", "<div>"); $html = $html.replace("</body></html>", "</div>"); $html = $($html); util.arrayLikePush(imgElements, $html.find("img")); } //圖片預加載 $("body").append(imageLoadDiv); $imageLoadDiv = $("#paste_image_load"); for(k = 0; k<imgElements.length; k++){ imgElements[k].onload = imgOnload; $imageLoadDiv.append(imgElements[k]); } } }, loadFinish = function(){ var dataurl = "", k = 0; if(imgElements.length === loadedCount){ //嘗試將圖像dom轉換成dataurl,如果失敗,返回img src for(k = 0;k<imgElements.length;k++){ dataurl = ""; dataurl = util.imageToDataUrl(imgElements[k]); if(dataurl){ htmlImages.push(dataurl); }else{ htmlImages.push(imgElements[k].getAttribute("src")); } } $("#paste_image_load").remove(); //返回結果 that.callback(htmlImages); } }, imgOnload = function(){ loadedCount = loadedCount+1; loadFinish(); }, imageLoadDiv = "<div id='paste_image_load' style='height: 0;width: 0;display: none;'></div>", i = 0; //提取html對象中的圖片 for(i = 0;i<htmlBlobs.length;i++){ htmlBlobs[i].getAsString(function(html){ htmlResults.push(html); parseFinish(); }); } }); }; Chrome.prototype.isSuport = function(){ return window.navigator.userAgent.toLowerCase().indexOf("chrome")>-1; }; //火狐瀏覽器和IE11瀏覽器算法 var FirefoxAndIE11 = util.extend(Strategy); FirefoxAndIE11.prototype.exec = function(){ var that = this, clipboardDiv = "<div id='paste_content_catch' contentEditable='true' style='position: fixed;left: -9999px;top: -9999px; opacity: 0;'></div>", $clipboardDiv = {}, i = 0; //初始化clipboard catch $("body").append(clipboardDiv); $clipboardDiv = $("#paste_content_catch"); //監聽ctrl+v事件 that.$element.on("keydown",function(event){ if(event.ctrlKey == 1 && event.keyCode == 86){ $clipboardDiv.html(""); $clipboardDiv.focus(); //模擬多線程 setTimeout(function(){ var id = "paste_image_load_" + new Date().getTime(), imageLoadDiv = "<div id='"+id+"' style='height: 0;width: 0;display: none;'></div>", $imageLoadDiv = {}, imageElements = [], images = [], loadedCount = 0; //獲取剪切板中的img元素 imageElements = $clipboardDiv.find("img"); //圖片預加載 $("body").append(imageLoadDiv); $imageLoadDiv = $("#"+id); for(i = 0;i<imageElements.length;i++){ imageElements[i].onload = function(){ var dataurl = "", k = 0; loadedCount = loadedCount+1; if(imageElements.length === loadedCount){ //嘗試將圖像dom轉換成dataurl,如果失敗,返回img src for(k = 0;k<imageElements.length;k++){ dataurl = ""; dataurl = util.imageToDataUrl(imageElements[k]); if(dataurl){ images.push(dataurl); }else{ images.push(imageElements[k].getAttribute("src")); } } $imageLoadDiv.remove(); //返回結果 that.callback(images); } }; $imageLoadDiv.append(imageElements[i]); } imageElements = $imageLoadDiv.find("img"); $clipboardDiv.html(""); that.$element.focus(); },0); } }); }; FirefoxAndIE11.prototype.isSuport = function(){ var result = false; try{ result = window.navigator.userAgent.toLowerCase().indexOf("firefox")>-1 || (Object.hasOwnProperty.call(window, "ActiveXObject") && !window.ActiveXObject); }catch(e){} return result; }; //選擇策略 for(i = 0;i<strategys.length;i++){ strategy = new strategys[i]({ $element: $(this), callback: callback }); if(strategy.isSuport()){ strategy.exec(); break; } } } }); })(jQuery,this);
c、demo.html
<body> <input type="text" id="container" placeholder="在這粘貼圖片"/> <script> $("#container").pasteImage(function(imgs){ $.each(imgs,function(i,n){ var imageData= n.replace("data:image/png;base64,", ""); var imageUrl="" $.ajax({ type: "POST", url: path+"/tmsSellMsg/uploadImageByBase64Code", data: {"imageData":imageData}, dataType: "json", async:false, success: function(data){ imageUrl = data; } }); $("body").append("<img src='"+imageUrl+"' >"); }); }); </script> </body>
d、springmvc
@RequestMapping(value = "/uploadImageByBase64Code", method = RequestMethod.POST) public @ResponseBody String insertTmsSellMsgByExcel2(String imageData) throws Exception { byte[] buf = Base64Utils.decodeFromString(imageData); InputStream sbs = new ByteArrayInputStream(buf); String imageUrl= OSSUtils.putObject(sbs); return JsonUtils.objectToJson(imageUrl); }
致此結束……
關注我的公眾號,精彩內容不能錯過