解决ueditor跨域上传文件失败的问题


最近正在做一个项目,用到了前后端分离的技术,前台使用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);
                    }  
                };  
            });

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM