|
参考文章 https://blog.csdn.net/Fiona_lms/article/details/80813112
<!doctype html>
<html lang="zh-cn">
<meta name="viewport" content="width=device-width, user-scalable=no">
<meta charset="UTF-8">
<head>
<title>lrz压缩插件</title>
</head>
<body>
<input type="file" name="file_head" class="inputfile1" accept="image/jpeg,image/png,image/jpg,image/gif" multiple="multiple"/>
<div id="inputfileimg"></div>
<!--图片放大-->
<script src="../lrz/lrz.bundle.js"></script>
<script src="../lrz/lrz.all.bundle.js"></script>
<script>
/*上传图片*/
$(".inputfile1").on("change", function(event) {
var files = this.files;
// 限制图片大小
if(this.files[0].size > ( 2*1024 * 1024)) {
lrz(this.files[0], {width: 300}).then(function (rst) {
if(rst.file.size> ( 2*1024 * 1024)){
layer.msg("图片大于2M", {
time: 3000
});
return;
}
var data=rst.base64;
data = data.split(',')[1];
data = window.atob(data);
var ia = new Uint8Array(data.length);
for(var i = 0; i < data.length; i++) {
ia[i] = data.charCodeAt(i);
}
var blob = new Blob([ia], {
type: "image/png",
endings: 'transparent'
});
var fd = new FormData();
fd.append('imgFile', blob, 'image.png');
fd.append('imgFile',rst.file);
fd.append("type", 3);
ajax.post(url, {
data: fd,
contentType: false, //不可缺
processData: false, //不可缺
success: function(data) {
$("#inputfileimg").html("<img src='" + res_url(data.data[0]) + "'/>");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus);
alert(textStatus);
}
});
}).catch(function (err) {
//捕获错误,而且一旦出错上面的then都不会执行
})
}else{
var fd = new FormData();
fd.append('imgFile', files[0]);
fd.append("type", 3);
imgFile(fd,$("#inputfileimg"));
}
})
/*
* 上传图片
* @param {*} postdata 接口传参
*/
function imgFile(postdata, imgobj) {
ajax.post(url, {
data: postdata,
contentType: false, //不可缺
processData: false, //不可缺
success: function(resp) {
if(resp.ok) {
imgobj.html("<img src='" + res_url(resp.data[0]) + "'/>");
} else {
utils.errorTips(resp.msg);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
layer.msg('error');
log(textStatus);
}
});
}
</script>
</body>
</html>
引入插件
|