.net core + angular 项目中使用ueditor遇到的问题

前言

这是两个问题,
1、angular中使用ueditor
2、.net core 中使用ueditor

.net core 中使用ueditor

在.net core中使用ueditor 主要是解决.net core中后台服务编写的问题。
使用UEditor.Core 或者UEditorNetCore都可以解决此问题。但是使用过程中可能会出现以下问题。

使用方法

1、安装nuget包
UEditor.Core 和UEditorNetCore 都可以使用,唯一的不同是api封装时有不同。不过也可也下载源码自行修改。
2、修改startup.cs
在ConfigureServices方法中添加如下内容

  //第一个参数为配置文件路径,默认为项目目录下config.json
  //第二个参数为是否缓存配置文件,默认false
services.AddUEditorService("config.json", true);

3、添加配置文件
从ueditor官网中下载的内容取出config.json文件添加进项目,就是上一步配置的路径及文件名。
以asp版本为例,


image.png

image.png

各个版本的这个文件应该可以通用。

image.png

配置文件中的说明已经很清楚了。

4、添加api
UEditor.Core中如下添加

    [Route("api/[controller]/[action]")]
    public class UEditorController : WeilaiCCMUControllerBase
    {
        private UEditorService ue;
        public UEditorController(UEditorService ue)
        {
            this.ue = ue;
        }
        [HttpGet, HttpPost]
        public ContentResult Do()
        {
            var response =  ue.UploadAndGetResponse(HttpContext);
            return Content(response.Result, response.ContentType);
        }
    }

UEditorNetCore 中如下添加

[Route("api/[controller]")] //配置路由
public class UEditorController : Controller
{
    private UEditorService ue;
    public UEditorController(UEditorService ue)
    {
        this.ue = ue;
    }

    public void Do()
    {
        ue.DoAction(HttpContext);
    }
}

常见问题

1、一般情况下, 在.net core 项目中,前台能访问的静态文件必须在wwwroot目录下面。解决的思路如下:

  • 修改配置, 把文件上传到wwwroot目录下面。修改代码,返回的相对路径不包含wwwroot路径。
  • 在startup.cs 文件Configure方法里添加如下设置。
    如果跟目录下没有upload会报错,此方法的作用就是让跟目录下upload内静态文件可以访问。
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
       Path.Combine(Directory.GetCurrentDirectory(), "upload")),
                RequestPath = "/upload",
                OnPrepareResponse = ctx =>
                {
                    ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=36000");
                }
            });

angular中使用ueditor

使用ngx-ueditor 基本可以解决问题。

具体参看官网:https://cipchk.github.io/ngx-ueditor

使用方法

1、安装npm 包

npm install ngx-ueditor 

2、添加模块
将ueditor官网下载的内容拷贝到工程目录下


image.png
import { UEditorModule } from 'ngx-ueditor'
        UEditorModule.forRoot({
            // 指定ueditor.js路径目录
            path: 'assets/uediter/',
            // 默认全局配置项
            options: {
                themePath: 'assets/uediter/themes/'
            }
        }),

3、使用

修改上面拷贝文件中的配置文件ueditor.config.js


image.png

html中

                        <ueditor [(ngModel)]="product.description"
                          [config]="{ initialFrameHeight: 300 }"
                          [loadingTip]="'加载中……'"></ueditor>

常见问题

1、在前后台分离的项目中,会出现部分功能不支持跨域功能而无法使用的(例如单文件上传)。解决思路如下,修改ueditor.all.js源码。修改单文件上传方法,改为post提交。


image.png

单文件上传的方法修改如下:

            utils.loadFile(document, {
                src: me.options.UEDITOR_HOME_URL + "third-party/jquery-1.10.2.min.js",
                tag: "script",
                type: "text/javascript",
                defer: "defer"
            });
            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')) {
                    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 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,
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        console.log("data:", data)
                        // data = JSON.parse(data);
                        var link, loader,
                            body = (iframe.contentDocument || iframe.contentWindow.document).body,
                            result = body.innerText || body.textContent || '';
                        var opt = me.options;
                        link = opt.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
                        });
                    }
                }
            });

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,107评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,149评论 6 342
  • 关于访谈对象杰里·波拉斯(Jerry I. Porras): 斯坦福大学商学院组织行为与变化学的教授。他是《流式分...
    ShadowSummer阅读 3,060评论 0 2
  • 今年目标:健康管理(早睡11点之前、饮食、体重) 黑色280 找到一位合作伙伴 今日青蛙:1.阅读。2.听音频。3...
    镇星Aquarius阅读 472评论 0 0
  • 一个月前,陈老师带着我们共读了英文版的《青鸟》。我们大家都非常喜欢共读英文版的《青鸟》,大家时常在课间聊起青鸟...
    白若菡阅读 5,105评论 3 3

友情链接更多精彩内容