当前位置: 首页 > Web前端 > vue.js

将图片的url解析为html并发送到自己的服务器

时间:2023-03-31 22:55:42 vue.js

处理要求:粘贴其他编辑器包含图片的内容时,需要将图片发送到自己的服务器。记录一下解决方法和踩过的坑。解析从剪贴板或界面获取的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)=>{//匹配匹配的整体值(这里是类似的内容)//捕获正则匹配的值(这里是shapeofhttp://www.xxxxx.com的图片链接地址)//排除自己的服务器地址if(capture.includes('www.xxxxx.com')){returnmatch}//this.count的初始值为0,imgs存储图片id和链接,方便通过操作dom替换内容constitem={url:capture,id:'pasteImg'+(++this.count)}imgs.push(item)//替换html中图片的地址,同时给每张图片分配idreturnmatch.replace(capture,'加载图片地址').replace(/{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的地址都处理完了。