前台图片压缩上传(Ajax_FormData)

 //表单
<form action="" method="post" enctype="multipart/form-data" id="frm">
<input type="file" name="image" accept="image/*" capture="camera" id="photos"/>
<img src="" id="ylimg" height="100%" />
<a class="submit" >确认</a>
</form>
//主要js
<script>
function uploadImg(parametric){var thisObj={maxWidth:parametric.maxNum||680,rate:parametric.rate||0.8,callback:parametric.callback||function(){alert("上传格式错误!")}}
$("#photos").on("change",function(e){if($(this).val()==""){return;}
var _this=this;var file=this.files[0];var reader0=new FileReader();var compressBas;reader0.readAsDataURL(file);reader0.onload=function(e){$(".utilsCover").css("display","block");var dataUrl=this.result;var fileType=file.type;var image=new Image();image.src=dataUrl;image.onload=function(e){var width=image.width,height=image.height;var scale=width/height;var canvas=document.createElement("canvas");var ctx=canvas.getContext('2d');ctx.clearRect(0,0,canvas.width,canvas.height);if(width-height>=0){width1=thisObj.maxWidth;height1=parseInt(width1/scale);if(width>=width1){canvas.width=width1;canvas.height=height1;ctx.drawImage(image,0,0,width1,height1);}else{canvas.width=width;canvas.height=height;ctx.drawImage(image,0,0,width,height);}}else{scale=height/width;height1=thisObj.maxWidth;width1=parseInt(height1/scale);if(height>=height1){canvas.width=width1;canvas.height=height1;ctx.drawImage(image,0,0,width1,height1);}else{canvas.width=width;canvas.height=height;ctx.drawImage(image,0,0,width,height);}}
var cropStr=canvas.toDataURL("image/jpeg",thisObj.rate);thisObj.callback(cropStr);}}})}
</script>
<script>
$(function(){
//开始调用
uploadImg({
maxNum: 680, //压缩后照片 最大宽度/高度
rate: 0.5, //清晰度比率 0-1 越小照片大小越小但越不清晰 默认0.8
callback: function (baseUrl) { // 回调函数返回压缩成功后的
$('#ylimg').attr('src',baseUrl)
//处理兼容
var width1 = $('#ylimg').width()
var hieght1 = $('#ylimg').height()
if(width1 < hieght1){
$('#ylimg').addClass('transform-rotate')
}
}
})
//转为blob
function dataURLtoFile(dataURI, type) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type:type });
}
$('.submit').click(function () {
var a = $('#ylimg').attr('src');
//调用对象
var file = new File([dataURLtoFile(a,'image/jpeg')], new Date()+'.jpg')
//创建FormData对象
var fd = new FormData();
fd.append("image", file);
$.ajax({
url:"{:url('portal/sign/sign')}",
data:fd,
type: 'POST',
dataType:'json',
processData:false,
contentType:false,
success:function (res) {
if(res.status==1){
layer.msg('success')
}
},
fail : function (res) {
layer.msg('当前网络波动较大,请重试')
}
});
}
}
})
})
</script>

点赞

发表评论