最近在做一个项目,需要用户截图后,将图片保存,上传到服务器。
传统的做法是,截图,保存文件到本地,在web页面上选择本地文件并上传。
现使用jquery及js插件实现,js插件是别人实现的,我只是修改了一些代码,结合flask,使之自动上传到服务,截图,复制到Input,然后自动显示在div上,并直接上传到服务,并把图片地址返回回来。
效果图如下:
image.png
html页面显示
<!doctype html>
<html>
<body>
<script src='js/jquery.min.js'></script>
<script src='js/screenshot-paaste.js'></script>
<input id='copyimg' tpye='text' placeholder='screenshots ctrl+v paste here'>
<span>return picurl</span><input id='rpic'>
<div id='imgPreview'></div>
<script type='text/javascript'>
$('#copyimg').screenshotPaste({
imgContainer:'#imgPreview', //view pic holder
imgHeight:50,
imgInputUrl:'#picurl'
})
</script>
</body>
</html>
js插件代码:
(function ($) {
$.fn.screenshotPaste=function(options){
var me = this;
if(typeof options =='string'){
var method = $.fn.screenshotPaste.methods[options];
if (method) {
return method();
} else {
return;
}
}
var defaults = {
imgContainer: '', //预览图片的容器
imgHeight:200, //预览图片的默认高度
imgIputUrl:'' //服务返回地址,放入图片input内
};
options = $.extend(defaults,options);
var imgReader = function( item ){
var file = item.getAsFile();
var reader = new FileReader();
reader.readAsDataURL( file );
reader.onload = function( e ){
var img = new Image();
img.src = e.target.result;
//ajax上传图片,返回图片地址
var imgurl;
$.ajax({
async:false,
type:"post",
url:'/updateImg',
data:{scr:img.src},
success:function(data,status){
if(status == "success"){imgurl=data.imgsrc;}
}
});
//return imgurl;
$(img).css({ height: options.imgHeight });
$(img).attr("onclick","javascript:showimage("+"'"+imgurl+"'"+")");
$(document).find(options.imgContainer)
.html('')
.show()
.append(img);
$(document).find(options.imgInputUrl)
.val(imgurl);
};
};
//事件注册
$(me).on('paste',function(e){
var clipboardData = e.originalEvent.clipboardData;
var items, item, types;
if( clipboardData ){
items = clipboardData.items;
if( !items ){
return;
}
item = items[0];
types = clipboardData.types || [];
for(var i=0 ; i < types.length; i++ ){
if( types[i] === 'Files' ){
item = items[i];
break;
}
}
if( item && item.kind === 'file' && item.type.match(/^image\//i) ){
imgReader( item );
}
}
});
$.fn.screenshotPaste.methods = {
getImgData: function () {
var src = $(document).find(options.imgContainer).find('img').attr('src');
if(src==undefined){
src='';
}
return src;
}
};
};
})(jQuery);
后台代码:
from flask import Flask,render_template,jsonify
import base64
import os
import time
app = Flask(__name__)
@app.route('/updateImg',methods=['GET','POST']
def updateImg():
base64img = request.form.get('scr')
strs = re.match('^data:imge/(jped|png|gif);base64,',base64img)
base64img = base64img.replace(strs.group(),'')
imgdata = base64.b64decode(base64img)
a,b = str(time.time()).split('.')
path = os.path.join('/picserver',a + '.png')
with open(path,'wb') as file:
file.write(imgdata)
return jsonify({'success':200,'imgsrc':path})
完成。github地址:https://github.com/hyzhangyong/flask-screenshot-paste
网友评论