简体   繁体   English

angular-ui-tinymce 指令和通过文件浏览器上传图像

[英]angular-ui-tinymce directive and image upload via file browser

With jquery we can add local images to tinymce editor like this jsfiddle following the documentation .使用 jquery 我们可以将本地图像添加到tinymce编辑器,就像这个 jsfiddle按照文档

The module for tinymce for angular is angular-ui-tinymce . tinymce的 tinymce 模块是angular-ui-tinymce But adding local file doesn't work with that module.但是添加本地文件不适用于该模块。

My code as follows.我的代码如下。 If it works there should be a file browse button like this when I click insert/edit image .如果它有效,当我单击insert/edit image时应该有一个这样的文件浏览按钮。 在此处输入图像描述

But it doesn't appear.但它没有出现。 Other than that everything works.除此之外,一切正常。 May be the module doesn't support that feature.可能是模块不支持该功能。 Does anyone know how to add local images with this module?有谁知道如何使用此模块添加本地图像?

in template:在模板中:

<textarea
    ui-tinymce="{{tinymceOptions}}"
    ng-model="tinymceValue">
</textarea>

in controller:在 controller 中:

 $scope.tinymceOptions: {
      selector: "textarea",
      plugins: 'image',
      file_browser_callback: function(){},
      paste_as_text: true
}

I use that directive in one of my apps and I can get that button to appear by using the using the file_browser_callback function in the options.我在我的一个应用程序中使用了该指令,并且可以通过使用选项中的file_browser_callback函数来显示该按钮。

Do you get any errors in the JavaScript console?在 JavaScript 控制台中是否有任何错误? Perhaps you can make a simple CodePen or JS Fiddle of this so people can see your code?也许您可以制作一个简单的 CodePen 或 JS Fiddle,以便人们可以看到您的代码?

EDIT: Here is a CodePen that does what you want ... it does get that button to appear.编辑:这是一个可以做你想做的事情的 CodePen ......它确实让那个按钮出现。 The file_browser_callback function just logs something to the browser's console but this shows that you can indeed have that button while using that Angular directive. file_browser_callback函数只是将一些内容记录到浏览器的控制台,但这表明您确实可以在使用该 Angular 指令时拥有该按钮。

http://codepen.io/michaelfromin/pen/BKOGZG http://codepen.io/michaelfromin/pen/BKOGZG

I found a solution my own with several research, trial and error its working fine for me in angular9.我通过多次研究、反复试验找到了我自己的解决方案,它在 angular9 中对我来说效果很好。 following are the steps I followed以下是我遵循的步骤

1 : Install & import ngx-tinymce refer https://www.npmjs.com/package/ngx-tinymce . 1:安装和导入 ngx-tinymce 参考https://www.npmjs.com/package/ngx-tinymce
2 : Following is the html snipet where [config]="textEditorConfig" you will point to the configurations of tinymce editor. 2 : 以下是 html snipet,其中 [config]="textEditorConfig" 您将指向 tinymce 编辑器的配置。

<div class="col-sm-12 col-md-12 col-lg-12">
    <label class="label modal-label text-uppercase">Texts</label>
        <tinymce
          *ngIf="viewMode?.key !== 'view'"
          #reportEditor
          formControlName="expectation"
          [config]="textEditorConfig"
        ></tinymce>
        <!--  View Mode -->
        <div class="template-view"
            *ngIf="viewMode?.key == 'view'"
             [innerHtml]="activityDetailForm?.value?.expectation">
         </div> 
 </div>

3 : Define tinymce configuration as follows 3:定义tinymce配置如下

public static htmlEditorConfig =  {
    height: 350,
    theme: 'modern',
    plugins: 'preview fullpage searchreplace directionality visualchars fullscreen  hr pagebreak nonbreaking anchor advlist lists textcolor wordcount contextmenu colorpicker textpattern link image media paste contextmenu',
    toolbar: 'formatselect | bold italic strikethrough forecolor backcolor | link autolink openlink unlink | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent | image media',
    contextmenu: 'paste link image',
    image_advtab: false,
    image_uploadtab: true,
    a11y_advanced_options: true,
    content_css: [
      '//fonts.googleapis.com/css?family=Raleway&display=swap',
      '//www.tinymce.com/css/codepen.min.css'
    ],

    file_picker_types: 'image',
    file_picker_callback: function (cb) {
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    input.onchange = function (e?: HTMLInputEvent) {
      var file = e.target.files[0];

      var reader = new FileReader();
      reader.onload = function (event) {
        console.log("tinymce",event)
        var blobCache =  event.target.result;
        var blobInfo = blobCache;
        cb(blobInfo, { title: file.name });
      };
      reader.readAsDataURL(file);
    };

    input.click();
    interface HTMLInputEvent extends Event {
      target: HTMLInputElement & EventTarget;
    }
  },
  };

YOUR HTML你的 HTML

<textarea data-ui-tinymce id="tinymce1" ng-model="data"></textarea>

<form id="image" style="width:0px;height:0;overflow:hidden">
    <input type="file" file-model="imageFile"/>
</form>

YOUR TINYMCE CONFIGURATION您的 TINYMCE 配置

tinymce.init({
    selector: 'textarea',

    automatic_uploads:true,
    file_browser_callback_types: 'file image media',
    file_browser_callback: function(field_name, url, type, win) {
        if(type=='image') {
            $('#editorImage input').click();
        }
    } 

});

YOUR DIRECTIVE你的指令

directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                    scope.uploadImage();
                });
            });
        }
    };
}]);

YOUR CONTROLLER FUNCTION您的控制器功能

$scope.uploadImage =function (){

    var fd = new FormData();
    fd.append('file', $scope.imageFile);
    $http({
        method:"POST",
        url: URL,
        data: fd,
        timeout:60000,
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).success(function(response,status){

    });

}

{{tinymceOptions}} in your html may not print the options where the value is a function. {{tinymceOptions}}在您的 html 中可能不会打印值为函数的选项。

So in your controller include 'uiTinymceConfig'所以在你的控制器中包含'uiTinymceConfig'

Then in your controller function然后在您的控制器功能中

uiTinymceConfig.file_browser_callback = function(){ debugger; };

angular-ui-tinymce merges 'tinymceOptions' (expression) and 'uiTinymceConfig' : angular-ui-tinymce 合并了 'tinymceOptions'(表达式)和 'uiTinymceConfig':

angular.extend(options, uiTinymceConfig, expression, setupOptions);

first create input element of type file and execute function click() to open dialog file selector, follow step is upload selected image (in my case I use ng-file-upload ) and retrieve the public url, remember use promises for wait user action, last step is set url in field of tinymce this is posible with field_name document.getElementById(field_name).value首先创建文件类型的输入元素并执行函数 click() 打开对话框文件选择器,按照步骤上传选定的图像(在我的情况下我使用ng-file-upload )并检索公共 url,记住使用 promises 等待用户操作, 最后一步是在 tinymce 的字段中设置 url 这可以使用 field_name document.getElementById(field_name).value

$scope.tinymceOptions = {
    selector: "textarea",
    plugins: 'image',
    file_browser_callback: function (field_name, url, type, win) {               
        let input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');            
        input.click();
        input.addEventListener('change', (event) => {
            let defered = $q.defer();
            Upload.upload({
                url: MultimediaService.uploadDocument(),
                data: {
                    file: event.path[0].files[0]
                }
            }).then(function (resp) {
                defered.resolve(resp);                        
            }, function (err) {
                defered.reject(err);
            });
            defered.promise.then(function (resp) {
                document.getElementById(field_name).value = resp['data']['url'];
                return resp['data']['url'];
            }, function (err) {
                return null;
            });
        });
    },
    paste_as_text: true
};

This has worked for me, used @tinymce/angular - angular version 11这对我有用,使用了@tinymce/angular - angular 版本 11

In component.html file在 component.html 文件中

<editor [id]="'editorID1'" style="margin-left: 0em" [formControlName]="'questiontext'" placeholder="Date"
       class="form-control" apiKey=" place your api key here" [init]="editorConfig">
</editor>

It's in ts file:它在 ts 文件中:

  let editorConfig = {
  paste_data_images: true,

  file_picker_callback: function(callback:any, value:any, meta:any) {
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
      if (meta.filetype == 'image') {
         input.click();
         // jQuery('#test-upload').trigger('click');
         //   input.on('change', function(e:any) {               
          input.onchange = function (e:any) {
          //jQuery('#test-upload').on('change', function(e:any) {
              var file:any = e.target.files[0];
              var reader = new FileReader();
              reader.onload = function(e: any) {
                  callback(e.target.result, {
                      alt: ''
                  });
              };
              reader.readAsDataURL(file);
          };
      }
  },

...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM