最近老特有点骚动,推特都被我们轰炸了,有点受不了,现在已经是赤裸裸的威胁了,哎,让我明白一个道理,以德服人是正途,但拳头大就是道理。
言归正传,自己搞了个电商项目,在后台添加产品的时候,可能绝大多数都是淘宝上的产品吧,一个一个扒图片下来,在排版编辑一个一个上传到编辑器里,这种枯燥无味的操作真的太痛苦了,我决定优化一下复制粘贴时自动下载网络图片并在对应位置替换成自己下载后的图片路径,其实很简单,来直接进入主题,编辑器都大同小异,我拿老王的编辑器(wangEditor)为例:
前端代码:
let editor = new weditor('#editor');
editor.customConfig.pasteTextHandle = function (content) {
// content 即粘贴过来的内容(html 或 纯文本),可进行自定义处理然后返回
//给内容里的IMG标签加上一个自适应宽度
let contenthtml = content.replace(/<img/g,'<img style="max-width:100%;"');
//获取内容中所有的img标签
let imgStrs = contenthtml.match(/<img.*?>/g);
//遍历img集合
$.each(imgStrs,function(i,img){
//获取img中的SRC路径
let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
let imgurl=img.match(srcReg)[1];
//将网络图片路径替换成加载中的图片并加上序号,方便替换本地图片
contenthtml=contenthtml.replace(imgurl,"../img/loading.gif?num="+i);
//图片下载接口返回对应的本地路径
$.ajax({
url: common.ctxPaths + '/onlinetopc',
type: 'POST',
dataType: 'json',
data: {
imgurl: imgurl,
},
success: function (data) {
if (data.code == 200) {
//将下载成功的图片路径替换到对应的位置
let url = "/static/editor/"+data.filename;
contenthtml=contenthtml.replace("../img/loading.gif?num="+i,url);
editor.txt.html(contenthtml);
}
}
})
})
return contenthtml
}
后端代码:
我的后端是用python+flask开发的
#图片线上转本地
@app.route("/adminapi/onlinetopc",methods=["post"])
def onlinetopc():
args = request.args if request.method == 'GET' else request.form
if not session.get('user'):
signresult={"code":209,"msg":"登录认证失败"}
return jsonify(signresult)
imgurl = args.get('imgurl', '')
response=requests.get(imgurl,timeout=30)
img = response.content
file_path_dir = os.path.join('app/static/editor')
if not os.path.exists(file_path_dir):
os.makedirs(file_path_dir)
filename = "e_{}.{}".format(uuid.uuid4(), "jpg")
file_path = os.path.join('{}/{}'.format(file_path_dir, filename))
with open(file_path, 'wb') as f:
f.write(img)
pinfo = {}
pinfo["code"] = 200
pinfo["filename"] = filename
return jsonify(pinfo)
后端就不用多说了,这里就是实现了下载网络图片保存到本地并返回对应的文件名,这里大家看下思路就行,具体的方法自己根据自己的代码实现,可以从上面看到,我是在each里面遍历的,比如有10张图片我就要遍历10次,这里你也可以提取内容中所有的图片进行一次上传,一次返回,可能处理的时间有点久,还可以结合websocket进行实时返回等等,方法太多了这里就不再一一说明了。
效果图:
嗯,一键粘贴就是爽!
关注我的公众号,一起在码农的道路上披荆斩棘!