参考 https://blog.csdn.net/wxw_nini/article/details/82463749 https://blog.csdn.net/Byte_Dance/article/details/87866929
js中
$("#btn").click(function () {
var sr = document.getElementById("ccc");
html2canvas(sr).then(function (canvas) {
window.html_canvas = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
var pHtml = "<img src="+window.html_canvas+" id='image_down'/>";
$('#html2canvas').html(pHtml);
// $('.ask_con').remove();
ceshi(window.html_canvas);
});
})
/**
* 把图片文件流保存到本地
*/
function ceshi(path){
$.ajax({
url:"{:url('admin/download/img')}",
data:{img:path},
type:'post',
dataType:'json',
success:function(res){
if(res.code == 200){
layer.msg('下载图片成功');
const url="http://dmp.51jcloud.com/"+res.data;
fetch(url).then(async res => await res.blob()).then((blob) => {
// 创建隐藏的可下载链接
const a = document.createElement('a');
a.style.display = 'none';
a.href = URL.createObjectURL(blob);
// 保存下来的文件名
// a.download = 'image.png';
a.download = res.name;
document.body.appendChild(a);
a.click();
// 移除元素
document.body.removeChild(a);
})
}else{
layer.msg('下载图片失败');
}
}
});
}
控制器
public function chart_img(){
$base64_string = $this->request->param('img');
$base64_string= explode(',', $base64_string); //截取data:image/png;base64, 这个逗号后的字符
$data= base64_decode($base64_string[1]);//对截取后的字符使用base64_decode进行解码
$url = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'images' . DS .time().rand(1000,9999).".png";
$res = file_put_contents($url, $data); //写入文件并保存到本地
$u = explode('/',$url);
$name = $u[7];
$downurl = 'uploads' . DS . 'images' . DS .$u[7];
if($res){
$da = [
'code'=>200,
// 'data'=>$url,
'data'=>$downurl,
'name'=>$name
];
}else{
$da = [
'code'=>403
];
}
return $da;
}
|