替換lib里的image-dialog.js
/*!
* Image (upload) dialog plugin for Editor.md
*
* @file image-dialog.js
* @author pandao
* @version 1.3.4
* @updateTime 2015-06-09
* {@link https://github.com/pandao/editor.md}
* @license MIT
*/
(function () {
var factory = function (exports) {
var pluginName = "image-dialog";
exports.fn.imageDialog = function () {
var _this = this;
var cm = this.cm;
var lang = this.lang;
var editor = this.editor;
var settings = this.settings;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var imageLang = lang.dialog.image;
var classPrefix = this.classPrefix;
var iframeName = classPrefix + "image-iframe";
var dialogName = classPrefix + pluginName, dialog;
cm.focus();
var loading = function (show) {
var _loading = dialog.find("." + classPrefix + "dialog-mask");
_loading[(show) ? "show" : "hide"]();
};
if (editor.find("." + dialogName).length < 1) {
var guid = (new Date).getTime();
var action = settings.imageUploadURL + (settings.imageUploadURL.indexOf("?") >= 0 ? "&" : "?") + "guid=" + guid;
if (settings.crossDomainUpload) {
action += "&callback=" + settings.uploadCallbackURL + "&dialog_id=editormd-image-dialog-" + guid;
}
action = '';
var dialogContent = ((settings.imageUpload) ? "<form action=\"" + action + "\" target=\"" + iframeName + "\" method=\"post\" enctype=\"multipart/form-data\" class=\"" + classPrefix + "form\">" : "<div class=\"" + classPrefix + "form\">") +
((settings.imageUpload) ? "<iframe name=\"" + iframeName + "\" id=\"" + iframeName + "\" guid=\"" + guid + "\"></iframe>" : "") +
"<label>" + imageLang.url + "</label>" +
"<input type=\"text\" data-url />" + (function () {
return (settings.imageUpload) ? "<div class=\"" + classPrefix + "file-input\">" +
"<input type=\"file\" name=\"" + classPrefix + "image-file\" accept=\"image/*\" />" +
"<input type=\"submit\" value=\"" + imageLang.uploadButton + "\" />" +
"</div>" : "";
})() +
"<br/>" +
"<label>" + imageLang.alt + "</label>" +
"<input type=\"text\" value=\"" + selection + "\" data-alt />" +
"<br/>" +
"<label>" + imageLang.link + "</label>" +
"<input type=\"text\" value=\"http://\" data-link />" +
"<br/>" +
((settings.imageUpload) ? "</form>" : "</div>");
//var imageFooterHTML = "<button class=\"" + classPrefix + "btn " + classPrefix + "image-manager-btn\" style=\"float:left;\">" + imageLang.managerButton + "</button>";
dialog = this.createDialog({
title: imageLang.title,
width: (settings.imageUpload) ? 465 : 380,
height: 254,
name: dialogName,
content: dialogContent,
mask: settings.dialogShowMask,
drag: settings.dialogDraggable,
lockScreen: settings.dialogLockScreen,
maskStyle: {
opacity: settings.dialogMaskOpacity,
backgroundColor: settings.dialogMaskBgColor
},
buttons: {
enter: [lang.buttons.enter, function () {
var url = this.find("[data-url]").val();
var alt = this.find("[data-alt]").val();
var link = this.find("[data-link]").val();
if (url === "") {
alert(imageLang.imageURLEmpty);
return false;
}
var altAttr = (alt !== "") ? " \"" + alt + "\"" : "";
if (link === "" || link === "http://") {
cm.replaceSelection("![" + alt + "](" + url + altAttr + ")");
} else {
cm.replaceSelection("[![" + alt + "](" + url + altAttr + ")](" + link + altAttr + ")");
}
if (alt === "") {
cm.setCursor(cursor.line, cursor.ch + 2);
}
this.hide().lockScreen(false).hideMask();
//刪除對(duì)話框
this.remove();
return false;
}],
cancel: [lang.buttons.cancel, function () {
this.hide().lockScreen(false).hideMask();
//刪除對(duì)話框
this.remove();
return false;
}]
}
});
dialog.attr("id", classPrefix + "image-dialog-" + guid);
if (!settings.imageUpload) {
return;
}
var fileInput = dialog.find("[name=\"" + classPrefix + "image-file\"]");
fileInput.bind("change", function () {
var fileName = fileInput.val();
var isImage = new RegExp("(\\.(" + settings.imageFormats.join("|") + "))$", "i"); // /(\.(webp|jpg|jpeg|gif|bmp|png))$/
if (fileName === "") {
alert(imageLang.uploadFileEmpty);
return false;
}
if (!isImage.test(fileName)) {
alert(imageLang.formatNotAllowed + settings.imageFormats.join(", "));
return false;
}
loading(true);
var submitHandler = function () {
var fileObj = dialog.find("[enctype=\"multipart/form-data\"]")[0];
compressFile(fileObj[1].files[0],function (files) {
var dic = new FormData();
dic.append('file', files);
$.ajax({
type: 'post',
// url: "http://localhost:8080/attachment/image/upload", // 你的服務(wù)器端的圖片上傳接口叼旋。如果你設(shè)置了 imageUploadURL超陆,那么可以使用下面的方式
url: settings.imageUploadURL + (settings.imageUploadURL.indexOf("?") >= 0 ? "&" : "?") + "guid=" + guid,
data: dic,
cache: false,
processData: false,
contentType: false,
success: function (data, textStatus, jqXHR) {
if (data.success === 1) { // 上傳成功
dialog.find("[data-url]").val("http://" + window.location.host + data.url); // 設(shè)置圖片地址
} else {
alert(data.message); // 上傳失敗只盹,彈出警告信息
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// console.log(XMLHttpRequest);
// console.log(textStatus);
// console.log(errorThrown);
}
});
});
loading(false); // 關(guān)閉加載效果
return false;
};
dialog.find("[type=\"submit\"]").bind("click", submitHandler).trigger("click");
});
}
dialog = editor.find("." + dialogName);
dialog.find("[type=\"text\"]").val("");
dialog.find("[type=\"file\"]").val("");
dialog.find("[data-link]").val("http://");
this.dialogShowMask(dialog);
this.dialogLockScreen();
dialog.show();
};
};
// CommonJS/Node.js
if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
module.exports = factory;
} else if (typeof define === "function") // AMD/CMD/Sea.js
{
if (define.amd) { // for Require.js
define(["editormd"], function (editormd) {
factory(editormd);
});
} else { // for Sea.js
define(function (require) {
var editormd = require("./../../editormd");
factory(editormd);
});
}
} else {
factory(window.editormd);
}
})();
然后壓縮方法 :
/**
* 壓縮圖片
* @param file input獲取到的文件
* @param callback 回調(diào)函數(shù),壓縮完要做的事忧便,例如ajax請(qǐng)求等。
*/
function compressFile(file, callback) {
var fileObj = file;
var reader = new FileReader()
reader.readAsDataURL(fileObj) //轉(zhuǎn)base64
reader.onload = function (e) {
var image = new Image() //新建一個(gè)img標(biāo)簽(還沒嵌入DOM節(jié)點(diǎn))
image.src = e.target.result
image.onload = function () {
var canvas = document.createElement('canvas'), // 新建canvas
context = canvas.getContext('2d'),
imageWidth = image.width / 2, //壓縮后圖片的大小
imageHeight = image.height / 2,
data = ''
canvas.width = imageWidth
canvas.height = imageHeight
context.drawImage(image, 0, 0, imageWidth, imageHeight)
data = canvas.toDataURL('image/jpeg') // 輸出壓縮后的base64
var arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1], // 轉(zhuǎn)成blob
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
var files = new window.File([new Blob([u8arr], {type: mime})], 'test.jpeg', {type: 'image/jpeg'}) // 轉(zhuǎn)成file
callback(files) // 回調(diào)
}
}
}