使用tinymce富文本编辑实现上传图片功能:
第一步:使用jquery.form.js插件;
自己去百度下载这个插件。
第二步:在angular2的目录中引入,如何引入:
在assets中建一个js文件夹,将jquery.form.js引入,
然后到.angular-cli.json 中添加代码
"scripts": [ "../node_modules/jquery/dist/jquery.min.js", "../src/assets/js/jquery.form.js" ],
将jquery.form.js插件引入。
第三步:
tinymce.init({ selector: '#post_editor', skin_url: '/assets/skins/lightgray', convert_urls: false, //menubar:false, // 'advlist autolink lists link image charmap print preview hr anchor pagebreak', // 'searchreplace wordcount visualblocks visualchars code fullscreen', // 'insertdatetime media nonbreaking save table contextmenu directionality', // 'emoticons template paste textcolor colorpicker textpattern imagetools codesample' plugins: [ 'advlist autolink lists link imageupload charmap preview hr anchor pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen', 'insertdatetime nonbreaking save table contextmenu directionality', 'emoticons template paste textcolor colorpicker textpattern codesample' ], toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link imageupload', toolbar2: 'print preview media | forecolor backcolor emoticons | codesample', imageupload_url: 'http://rapapi.org/mockjsdata/20823/upload/images', //image_advtab: true, codesample_content_css: '/assets/css/prism.css', //文件和图片上传相关的选项 file_browser_callback_types: 'image', file_browser_callback: function (field_name, url, type, win) { console.log(type); console.log(type == 'image'); if (type == 'image') { let event = new MouseEvent('click', { 'view': window, 'bubbles': true, 'cancelable': true }); let fileInput = document.getElementById('img_input'); fileInput.dispatchEvent(event); } }, setup: editor => { // editor.setContent("12345"); this.editor = editor; editor.on('blur', () => { this.tinymceContent.left = editor.getContent(); this.RichTextGoOut.emit(this.tinymceContent); // this.content = editor.getContent(); }); editor.addButton('mybutton', { text: '上传图片', icon: false, onclick: function () { $("input[name='upload-img']").click(); } }) } }); }
在plugins添加插件功能 imageupload,在toolbar1中添加imageupload,
imageupload_url: 'http://rapapi.org/mockjsdata/20823/upload/images',
在最后添加editor.addButton等内容。
第三步:上传之后后端会返回展示的image 的url,到node_modules/tinymce/plugins/imageupload/plugin.min.js中修改img的src.
var submitUpload = function(){ $('#uploadImageForm').ajaxSubmit({ dataType: 'json', success: function(response){ console.log(response) var tpl = ''; ed.insertContent(tpl.replace('%s', response.path)); ed.focus(); removeForeground(); removeBackground(); }, error: function(){ showImageUploadError('上传错误:2'); } }); }
完美解决图片上传功能,动态显示在了框内。
还有一个:tinymce需要升级到4.5.6版本才能用
还看不懂就去看我的代码吧:
https://git.oschina.net/kaykie/unique