最近在使用百度ueditor富文本編輯器拌屏,由于是一個(gè)前后端分離的項(xiàng)目肋层,并且需要使用單圖上傳的功能塘匣,所以不可避免的會(huì)產(chǎn)生跨域問題蛉鹿,先來看看官方給的說法:
單圖上傳暫時(shí)不支持跨域設(shè)置齐媒,為了兼容低版本瀏覽器蒲每,使用了提交表單到iframe提交。通過iframe的onload事件喻括,觸發(fā)回調(diào)函數(shù)邀杏,這時(shí)候再讀取iframe里面的內(nèi)容,得到的服務(wù)器返回?cái)?shù)據(jù)唬血。 跨域情況下望蜡,產(chǎn)生了跨域的iframe訪問,可以解決方法都需要前后端一起改變拷恨。要解決這個(gè)問題泣特,小伙伴們發(fā)揮想象力吧。
可以說相當(dāng)?shù)牟回?fù)責(zé)任了哈哈挑随,先不吐槽這個(gè)状您。
首先來看看問題是怎么產(chǎn)生的,谷歌chrome下配置好ueditor之后直接點(diǎn)擊單圖上傳勒叠,沒有任何反應(yīng),別急膏孟,看一眼Network
可以看到服務(wù)器有返回信息眯分,但為什么編輯器中沒有回顯成功呢?
我們定位到ueditor.all.js這個(gè)文件柒桑,看看單圖上傳時(shí)都做了些什么
定位到這一段代碼(在24500行左右弊决,我的源文件修改過了,可能有所不同)
domUtils.on(input, 'change', function(){
if(!input.value) return;
var loadingId = 'loading_' + (+new Date()).toString(36);
var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName')); 2
var allowFiles = me.getOpt('imageAllowFiles');
me.focus();
me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme +'/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
function callback(){
try{
var link, json, loader,
body = (iframe.contentDocument || iframe.contentWindow.document).body,
result = body.innerText || body.textContent || '';
json = (new Function("return " + result))();
link = me.options.imageUrlPrefix + json.url;
if(json.state == 'SUCCESS' && json.url) {
loader = me.document.getElementById(loadingId);
loader.setAttribute('src', link);
loader.setAttribute('_src', link);
loader.setAttribute('title', json.title || '');
loader.setAttribute('alt', json.original || '');
loader.removeAttribute('id');
domUtils.removeClasses(loader, 'loadingclass');
} else {
showErrorLoader && showErrorLoader(json.state);
}
}catch(er){
showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
}
form.reset();
domUtils.un(iframe, 'load', callback);
}
function showErrorLoader(title){
if(loadingId) {
var loader = me.document.getElementById(loadingId);
loader && domUtils.remove(loader);
me.fireEvent('showmessage', {
'id': loadingId,
'content': title,
'type': 'error',
'timeout': 4000
});
}
}
/* 判斷后端配置是否沒有加載成功 */
if (!me.getOpt('imageActionName')) {
console.log(1)
errorHandler(me.getLang('autoupload.errorLoadConfig'));
return;
}
// 判斷文件格式是否錯(cuò)誤
var filename = input.value,
fileext = filename ? filename.substr(filename.lastIndexOf('.')):'';
if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
console.log(2)
showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
return;
}
domUtils.on(iframe, 'load', callback);
form.action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?':'&') + params);
form.submit();
});
可以看到有一個(gè)try魁淳,catch語(yǔ)句飘诗,正是在這里出現(xiàn)了跨域錯(cuò)誤
console.log((iframe.contentDocument || iframe.contentWindow.document).body);
try{
var link, json, loader,
body = (iframe.contentDocument || iframe.contentWindow.document).body,
result = body.innerText || body.textContent || '';
json = (new Function("return " + result))();
link = me.options.imageUrlPrefix + json.url;
if(json.state == 'SUCCESS' && json.url) {
loader = me.document.getElementById(loadingId);
loader.setAttribute('src', link);
loader.setAttribute('_src', link);
loader.setAttribute('title', json.title || '');
loader.setAttribute('alt', json.original || '');
loader.removeAttribute('id');
domUtils.removeClasses(loader, 'loadingclass');
} else {
showErrorLoader && showErrorLoader(json.state);
}
}catch(er){
showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
}
隨便console一下,出現(xiàn)如下報(bào)錯(cuò)
Uncaught DOMException: Blocked a frame with origin "###" from accessing a cross-origin frame.at HTMLIFrameElement.callback (###)界逛。
這個(gè)其實(shí)就是游覽器出于安全考慮昆稿,禁止iframe跨域訪問,而官方也說了:
那么怎么解決iframe跨域的問題呢息拜,找到了問題所在溉潭,解決起來就簡(jiǎn)單了,我試了兩種方法少欺,介紹一下:
第一種喳瓣,使用new FormData()來提交;
除開不兼容ie9及以下版本之外赞别,幾乎是最好用的畏陕,廢話不多說,直接貼代碼仿滔;直接替換掉上文的那一段源文件代碼就ok
domUtils.on(input, 'change', function() {
if(!input.value) return;
var loadingId = 'loading_' + (+new Date()).toString(36);
var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
var allowFiles = me.getOpt('imageAllowFiles');
me.focus();
me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme +'/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
//!* 判斷后端配置是否沒有加載成功 *!/
if (!me.getOpt('imageActionName')) {
console.log(11)
errorHandler(me.getLang('autoupload.errorLoadConfig'));
return;
}
// 判斷文件格式是否錯(cuò)誤
var filename = input.value,
fileext = filename ? filename.substr(filename.lastIndexOf('.')):'';
if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
return;
}
var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
var action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?' : '&') + params);
var formData = new FormData();
formData.append("upfile", form[0].files[0] );
$.ajax({
url: action,
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false,
success: function (data) {
data = JSON.parse(data);
var link, loader,
body = (iframe.contentDocument || iframe.contentWindow.document).body,
result = body.innerText || body.textContent || '';
link = me.options.imageUrlPrefix + data.url;
if(data.state == 'SUCCESS' && data.url) {
loader = me.document.getElementById(loadingId);
loader.setAttribute('src', link);
loader.setAttribute('_src', link);
loader.setAttribute('title', data.title || '');
loader.setAttribute('alt', data.original || '');
loader.removeAttribute('id');
domUtils.removeClasses(loader, 'loadingclass');
} else {
showErrorLoader && showErrorLoader(data.state);
}
form.reset();
}
});
function showErrorLoader(title){
if(loadingId) {
var loader = me.document.getElementById(loadingId);
loader && domUtils.remove(loader);
me.fireEvent('showmessage', {
'id': loadingId,
'content': title,
'type': 'error',
'timeout': 4000
});
}
}
});
第二種方式 依然使用iframe來進(jìn)行提交
為什么還要使用iframe蹭秋,因?yàn)槲覀兊膇e(6~9)不支持new FormData(),那就還得從iframe這種方式入手,官方也提到了從iframe入手其實(shí)也可以解決:跨域情況下堤撵,產(chǎn)生了跨域的iframe訪問仁讨,可以解決方法都需要前后端一起改變。要解決這個(gè)問題实昨,小伙伴們發(fā)揮想象力吧洞豁。
跨域情況下,其實(shí)是無法訪問iframe內(nèi)的body內(nèi)容的荒给,也就是圖片可以上傳到后臺(tái)丈挟,但是前端無法獲取回調(diào)信息,也就是說正常途徑下志电,前端無法實(shí)現(xiàn)回顯曙咽。
那么解決思路就來了,既然是由iframe跨域產(chǎn)生的問題挑辆,那我們就可以從iframe跨域入手例朱,后端處理這條請(qǐng)求后孝情,重定向至前端的一個(gè)空html頁(yè)面,將所有的回調(diào)參數(shù)放到url中~