您的当前位置:首页>全部文章>文章详情

TinyMCE version 6.0.1 粘贴稿件自动下载并上传远程图片的代码

发表于:2025-01-09 17:20:49浏览:243次TAG: #ThinkPHP #果子CMS系统 #elementUi #图片本地化

在cms系统开发应用中经常会遇到粘贴图片到编辑器,稿件中的远程图片到生成的文章中不可以的现象,经过两天的调试粘贴图文时一次性的把远程图片本地化(上传到网站服务器),改造的是Tinymce 6.0.1,其他版本没有测试。

系统环境:Vue2+element UI + ThinkPHP8

直接上代码:

1、首先提取粘贴图片的地址,其中只提取 <img src=”图片地址“,其他如 data-img="图片地址“等一律忽略,比如我的这种情况

1、定义方法:extractImages 

2、获取图片地址

const imageUrls = t.extractImages(e.getContent());

3、如果获取到图片,循环图片并上传到服务器

if(imageUrls.length>0){
						for(var i=0; i<imageUrls.length; i++){
							var fileUrl = imageUrls[i];
							console.log(fileUrl)
							const imageName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
							fetch(fileUrl)
								.then(response => response.blob())
								.then(blob => {
									console.log(blob)
									let formdata = new FormData()
									formdata.append('file', blob, imageName)
									formdata.append('edit', true)
									axios.post(base_url+'/Upload/upload', formdata).then(res => {
										console.log(res)
										e.setContent(e.getContent().replace(t.url,res.data.data))
									})
								})

						}
					}

4、说明,这里要做编辑器触发粘贴动作时执行,所以。。。完整代码如下

init_instance_callback: function(e) {
				e.on("Change KeyUp Undo Redo",
				function(n) {
					t.$emit('update:content',e.getContent())
				}),
					// 在编辑器中粘贴时触发
				e.on('paste', function (el) {

					const imageUrls = t.extractImages(e.getContent());

					if(imageUrls.length>0){
						for(var i=0; i<imageUrls.length; i++){
							var fileUrl = imageUrls[i];
							console.log(fileUrl)
							const imageName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
							fetch(fileUrl)
								.then(response => response.blob())
								.then(blob => {
									console.log(blob)
									let formdata = new FormData()
									formdata.append('file', blob, imageName)
									formdata.append('edit', true)
									axios.post(base_url+'/Upload/upload', formdata).then(res => {
										console.log(res)
										e.setContent(e.getContent().replace(t.url,res.data.data))
									})
								})

						}
					}

				}),
				t.objTinymce = e
			},