最终代码:
一、分析遇到的问题:
在上传图片的时候会显示跨域的问题
后端也配置了跨域的问题
@RestController @RequestMapping("/rest/agriculture/productController") @Api("商品管理") @CrossOrigin public class ProductController
很明显不是后端的问题,其他的图片都可以进行上传,如下,唯独使用editor.md无法进行上传。
二、解决问题
js配置如下:
//初始化Markdown的编辑区 var testEditor = editormd({ id : "test-editormd", width : "100%", height : 640, syncScrolling : "single", path : "res/editormd/lib/", placeholder : "请填写商品的详细描述信息", emoji:true, /**上传图片相关配置如下*/ imageUpload : true ,imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"] ,saveHTMLToTextarea: true//注意:这个配置,方便post提交表单 ,crossDomainUpload : true ,imageUploadURL : ServerIP+"/rest/agriculture/productController/addProductImage"//上传图片的的地址 });
关键代码:
/**上传图片相关配置如下*/ imageUpload : true ,imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"] ,saveHTMLToTextarea: true//注意:这个配置,方便post提交表单 ,crossDomainUpload : true ,imageUploadURL : ServerIP+"/rest/agriculture/productController/addProductImage"//上传图片的的地址
后端代码:
String homeDisplayDrawingImageUrl = ossUtil.checkImage(attach);
此代码只是我封装的上传倒阿里云OOS的一个工具类。可以忽略,你可以保存到自己的本地。如果你想保存到本地的话,可以参考我附加的文章地址,查看即可解决。
/** * 上传商品简介内容中的插入的单张图 * @param attach * @return */ @ResponseBody @RequestMapping(value = "/addProductImage", method = RequestMethod.POST) @ApiOperation("上传商品简介内容中的插入的单张图") public String addProductImage(@RequestParam(value = "editormd-image-file", required = false) MultipartFile attach) { JSONObject jsonObject=new JSONObject(); //上传商品简介内容中的,单张图 String homeDisplayDrawingImageUrl = ossUtil.checkImage(attach); try { // 下面response返回的json格式是editor.md所限制的,规范输出就OK jsonObject.put("success", 1); jsonObject.put("message", "上传成功"); jsonObject.put("url", homeDisplayDrawingImageUrl); } catch (Exception e) { jsonObject.put("success", 0); } System.out.println(jsonObject.toString()); return jsonObject.toString(); }
至于传值为什么要这样写:editormd-image-file
@RequestParam(value = "editormd-image-file", required = false) MultipartFile attach
可以打开前端,使用控制台看一下这个的name,就是这个;如果想改的话,就去改源代码了。
解决问题的重要代码:
需要找到admin/res/editormd/plugins/image-dialog/image-dialog.js
这个js文件,因为要修改这的源代码,可以根据自己项目的路径参考我的地址来找到。
原来的代码:
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 dialogContent = ( (settings.imageUpload) ? "<form 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\" id=\"" + 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>");
原来的:
uploadIframe.onload = function() { loading(false); var body = (uploadIframe.contentWindow ? uploadIframe.contentWindow : uploadIframe.contentDocument).document.body; var json = (body.innerText) ? body.innerText : ( (body.textContent) ? body.textContent : null); json = (typeof JSON.parse !== "undefined") ? JSON.parse(json) : eval("(" + json + ")"); console.log(json); if(!settings.crossDomainUpload) { if (json.success === 1) { dialog.find("[data-url]").val(json.url); } else { alert(json.message); } } return false; };
修改成:
uploadIframe.onload = function() { loading(false); //这是我个人写法 var formData = new FormData(); formData.append("editormd-image-file",$("#editormd-image-file")[0].files[0]); var action = settings.imageUploadURL + (settings.imageUploadURL.indexOf("?") >= 0 ? "&" : "?") + "guid=" + guid; console.log(formData); $.ajax({ type:"post", url:action, data:formData, dataType:"json", async:false, processData : false, // 使数据不做处理 contentType : false, // 不要设置Content-Type请求头 success:function(data){ // 成功拿到结果放到这个函数 data就是拿到的结果 console.log(data); if(data.success == 1){ console.log(data.message); dialog.find("[data-url]").val(data.url); }else{ alert(data.message); } }, }); return false; };
全部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; } /* 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 dialogContent = ( (settings.imageUpload) ? "<form 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\" id=\"" + 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(); //删除对话框 this.remove(); return false; }], cancel : [lang.buttons.cancel, function() { this.hide().lockScreen(false).hideMask(); //删除对话框 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 uploadIframe = document.getElementById(iframeName); uploadIframe.onload = function() { loading(false); /*var body = (uploadIframe.contentWindow ? uploadIframe.contentWindow : uploadIframe.contentDocument).document.body; var json = (body.innerText) ? body.innerText : ( (body.textContent) ? body.textContent : null); json = (typeof JSON.parse !== "undefined") ? JSON.parse(json) : eval("(" + json + ")"); console.log(json); if(!settings.crossDomainUpload) { if (json.success === 1) { dialog.find("[data-url]").val(json.url); } else { alert(json.message); } } return false;*/ //这是我个人写法 var formData = new FormData(); formData.append("editormd-image-file",$("#editormd-image-file")[0].files[0]); var action = settings.imageUploadURL + (settings.imageUploadURL.indexOf("?") >= 0 ? "&" : "?") + "guid=" + guid; console.log(formData); $.ajax({ type:"post", url:action, data:formData, dataType:"json", async:false, processData : false, // 使数据不做处理 contentType : false, // 不要设置Content-Type请求头 success:function(data){ // 成功拿到结果放到这个函数 data就是拿到的结果 console.log(data); if(data.success == 1){ console.log(data.message); dialog.find("[data-url]").val(data.url); }else{ alert(data.message); } }, }); 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); } })();
三、效果
可参考地址:
https://blog.csdn.net/ELOVINFG/article/details/103048813
https://www.cnblogs.com/softidea/p/7808214.html
四、快看,小郑有话对你说
如果对你有帮助,可以分享给你身边的朋友。或者给俺点个大大的赞和大大的评论,点赞和评论就是给我最大的支持,感谢。
水平有限,难免会有疏漏或者书写不合理的地方,欢迎交流讨论。