之我有一篇文章寫到了,怎麼處理富文本上傳圖片後單用戶刪除了,造成服務器大量垃圾圖片的問題,解決方案請戳鏈接
怎麼保證用富文本編輯器不讓服務器產生垃圾圖片,神器redis的發佈訂閱
做富文本編輯器發佈文章的時候,有這樣一個需求,就是直接使用qq的快捷鍵截圖,然後直接在富文本編輯器把圖片粘貼了,然後圖片就可以自動上傳到服務器,我測試了一些富文本有的是可以實現了的,但summernote就沒有實現,但我想用這個怎麼辦,於是就搜索整合出瞭解決方案。
實現原理就是,js直接監聽鼠標的粘貼事件,如果粘貼的內容含有圖片,就直接上傳到服務器,並將圖片顯示在頁面上!
下面是關鍵代碼:
獲取編輯框,添加監聽粘貼事件:
//summernote
//監聽粘貼圖片
document.getElementsByClassName('note-editable')[0].addEventListener('paste',function(e){
if ( !(e.clipboardData && e.clipboardData.items) ) {
return;
}
for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
var item = e.clipboardData.items[i];
if (item.kind === "string") {
item.getAsString(function (str) {
console.log(str);
})
} else if (item.kind === "file") {
var f= item.getAsFile();
parseFile(f, 800,function(base64){
$.post("/manager/uploadImg",{"imgStr":base64},function(data){
$('#summernote').summernote('editor.insertImage', data.msg);
});
})
console.log(f);
}
}
});
這裏說明一下這個parseFile方法,就是將圖片轉化爲base64編碼,並壓縮base64編碼,然後上傳到服務器。
代碼我也貼出來吧:
//壓縮方法
function parseFile(file, w,callBack) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){
var newImage = new Image();
var quality = 0.7; //壓縮係數0-1之間
newImage.src = reader.result;
console.log("原來長度",reader.result.length)
newImage.setAttribute("crossOrigin", 'Anonymous'); //url爲外域時需要
var imgWidth, imgHeight;
newImage.onload = function () {
imgWidth = this.width;
imgHeight = this.height;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
if (Math.max(imgWidth, imgHeight) > w) {
if (imgWidth > imgHeight) {
canvas.width = w;
canvas.height = w * imgHeight / imgWidth;
} else {
canvas.height = w;
canvas.width = w * imgWidth / imgHeight;
}
} else {
canvas.width = imgWidth;
canvas.height = imgHeight;
quality = 0.7;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
var base64 = canvas.toDataURL("image/jpeg", quality); //壓縮語句
// 如想確保圖片壓縮到自己想要的尺寸,如要求在50-150kb之間,請加以下語句,quality初始值根據情況自定
while (base64.length / 1024 > 100) {
quality -= 0.01;
base64 = canvas.toDataURL("image/jpeg", quality);
}
// 防止最後一次壓縮低於最低尺寸,只要quality遞減合理,無需考慮
// while (base64.length / 1024 < 50) {
// quality += 0.001;
// base64 = canvas.toDataURL("image/jpeg", quality);
// }
console.log("壓縮後長度",base64.length)
callBack(base64)
}
}
}
利用這個思路,基本上可以應對任何的富文本了吧,只要支持上傳方法重寫就可以!