js base64 转成图片上传
直接上代码,要点就是把base64转成Blob,添加到FormData传递给后台程序,跟选择图片文件上传时一样的了。
var dataurl = canvas.toDataURL('image/png'); //base64图片数据
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);
}
var obj = new Blob([u8arr], {type:mime});
var fd = new FormData();
fd.append("upfile", obj,"image.png");
$.ajax({
url: "/file/upfile",
type: "POST",
processData: false,
contentType: false,
data: fd,
success: function (data) {
console.log(data);
}
});
//canvas保存图片到本地
(function(t){
var dlLink = t || document.createElement("a");
if(!t){
dlLink.id='dlLink';
dlLink.download = '文件名';
document.body.appendChild(dlLink);
}
dlLink.href = dataurl;
dlLink.click();
})(document.querySelector("#dlLink"));