处理要求:粘贴其他编辑器包含图片的内容时,需要将图片发送到自己的服务器。记录一下解决方法和踩过的坑。解析从剪贴板或界面获取的html字符串,需要解析所有涉及的图片。这里我们使用正则表达式。让htmlContent='获取html字符串'const{content,imgs}=this.getHtmlAndImgs(htmlContent)htmlContent=contentimgs.forEach(asyncitem=>{constformData=awaitthis.imgUrlToFomdata(item.url)this.uploadToServer(formData,item.id)})getHtmlAndImgs(htmlContent){constimgs=[]htmlContent=htmlContent.replace(/]*src=['"]([^'"]+)[^>]*>/gi,(match,capture)=>{//匹配匹配的整体值(这里是类似
{fetch(url).then(respone=>respone.blob()).then(blob=>{constformData=newFormData();const{type}=blobconstimgSuffix=type.substring(6)//如果不设置名称和后缀,接口会报错401,看后端接口代码constfileName=`${newDate().getTime()}.${imgSuffix}`constfile=newFile([blob],fileName,{type});formData.append('file',file,fileName);resolve(formData)}).catch(error=>{reject(error)});})}上传图片到服务器将转换后的formdata二进制文件上传到服务器,图片地址通过id重置为自己服务器的地址。asyncuploadToServer(formData,id){constres=awaitthis.$api.upload.blogImgUpload(formData);}const{代码,数据,消息}=res.data;if(code===200){//我的编辑器使用了tinymce,获取编辑器内容的dom元素需要通过activeEditor.activeEditor.getBody().querySelector(`#${id}`).src=数据;}else{this.$message.error(消息);}}至此,处理html和设置img的地址都处理完了。
