最近正在做一個項目,用到了前后端分離的技術,前台使用ueditor時,跨域上傳文件會提示失敗,網上搜了很多方案,都看的一頭霧水,正好自己琢磨一下,就用h5的Formdata和xmlHttpRequest可以完美解決,關於瀏覽器兼容文件大家可以自己再想辦法解決,下面就記錄一下具體解決方案。
- 服務端的跨域配置(這里是用springboot配置的跨越)
private CorsConfiguration buildConfig()
{
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setMaxAge(3600L);
List<String> urlArr = new ArrayList<String>();
urlArr.add("*");
corsConfiguration.setAllowedOrigins(urlArr);
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter()
{
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
-
服務端返回的JSON字符串格式:
服務端上傳完之后,返回的結果必須包含state字段和url字段,state返回SUCCESS或者其他,url返回圖片的顯示地址.
- 客戶端代碼修改(改造了ueditor.all.js第24505行的domUtils方法,直接復制下面的代碼替換之前的方法就可以)
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'));
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(responseData){
try{
if(responseData.state == 'SUCCESS' && responseData.url) {
loader = me.document.getElementById(loadingId);
loader.setAttribute('src', responseData.url);
loader.setAttribute('_src', responseData.url);
loader.setAttribute('title', responseData.title || '');
loader.setAttribute('alt', responseData.original || '');
loader.removeAttribute('id');
domUtils.removeClasses(loader, 'loadingclass');
} else {
showErrorLoader && showErrorLoader(responseData.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')) {
errorHandler(me.getLang('autoupload.errorLoadConfig'));
return;
}
// 判斷文件格式是否錯誤
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 fileForm = new FormData();
fileForm.append("userFile",input.files[0]);
var oReq = new XMLHttpRequest();
oReq.open("POST",imageActionUrl,true);
oReq.send(fileForm); // 使用XMLHttpRequest的send()把數據發送出去
oReq.onreadystatechange = function(responseText) {//服務器返回值的處理函數,此處使用匿名函數進行實現
if (oReq.readyState == 4 && oReq.status == 200) {//
var responseData = eval("("+oReq.responseText+")");
callback(responseData);
}
};
});
