签名demo:https://github.com/xuyongsky123/canvasSignature (侵删)
作出适当修改放入我的网站里面
解决:绑定canvas容器touchmove
//阻止签名时页面拖拽
document.getElementById("signatureTab").addEventListener('touchmove', function (e) {
e.preventDefault();
}, { passive: false });
解决:动态引入js css
/**
* 动态加载js
* @param url
* @param callback
*/
function loadJS( url, callback ){
var script = document.createElement('script'),
fn = callback || function(){};
script.type = 'text/javascript';
//IE
if(script.readyState){
script.onreadystatechange = function(){
if( script.readyState == 'loaded' || script.readyState == 'complete' ){
script.onreadystatechange = null;
fn();
}
};
}else{
//其他浏览器
script.onload = function(){
fn();
};
}
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
//用法
// loadJS('file.js',function(){});
}
// 动态加载css
function loadStyle(url) {
var link = document.createElement('link');
link.rel = "stylesheet";
link.type = "text/css";
link.href = url;
var head = document.getElementsByTagName("head")[0];
head.appendChild(link);
};
解决:如果直接将base64转换成file,某些系统(例如ios)会不兼容,可以尝试先将base64转换成blob,再将blob转换为file
//将base64转换为blob
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};
//将blob转换为file
function blobToFile(theBlob, fileName){
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
};
$("#supplyMyResult").on('click',function(){
//生成图片格式base64包括:jpg、png格式
var blob = dataURLtoBlob($('#signName').createSignature('png'));
var file = blobToFile(blob, "imgSignature");
//这里我打算用ajax方式,所以需要使用Formdata形式
var data=new FormData();
data.append("file",file);
$.ajax({
url:"接口地址",
type:"POST",
dataType:"JSON",
data:data,
contentType: false,
processData: false,
success:function(res){
console.log(res);
}
});
});
解决:使用Multipart(我这里使用的是springboot)
//返回文件上传后的路径
@PostMapping("接口")
public synchronized String 接口(MultipartHttpServletRequest request) throws IOException {
MultipartFile file = request.getFile("file");
String resultUrl;
byte[] bytes = file.getBytes();
resultUrl = fileUtil.singleUpload("路径", bytes, ".png");
return resultUrl;
}
singleUpload 函数
/**
* 单文件上传
*
* @param path
* @param file
* @param fix
* @return
*/
public static synchronized String singleUpload(String path, byte[] file, String fix) {
String ROOT_PATH="根目录";
TimeUtil timeUtil = new TimeUtil();//避免重名
File targetFile = new File(ROOT_PATH+path);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = null;
String fileName=timeUtil.dateToRandom(5);
try {
out = new FileOutputStream(ROOT_PATH+path + fileName + fix);
out.write(file);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return path + fileName + fix;
}
效果