引入一个js:
<script src="../../js/compressPhotoUpload.min.js"></script>
百度网盘链接:https://pan.baidu.com/s/1KO9gH4r6bP-foYVAQn5AxQ
提取码:mgcm
复制这段内容后打开百度网盘手机App,操作更方便哦
html:(@change="changeImage($event)" 触发选择图片)
<div class="bq-mid">
<div class="bq-ai-image" v-for="(item,index) in pubImage">
<img class="bq-img-add" :src="imgUrl + item" @click.stop="delImg(index)">
</div>
<div class="bq-ai-add-img">
<input type="file" name="file" id="input" class="bq-sc" ref="qrCodefile"
accept="image/*" @change="changeImage($event)">
<img src="../../image/pub_pw_addImg.png" class="bq-ppi-add-img">
</div>
</div>
业务逻辑:
//添加图片
changeImage(e) {
let reader = new FileReader();//创建文件对象
let z = new zz();//创建压缩对象
reader.readAsDataURL(e.target.files[0]);
reader.onload = function (e) {
$('#loading').show();
let ImgFile = this.result;
//如果图片大于2M就压缩,否则直接上传
if (ImgFile.length / (1024 * 1024) > 2) {
z.compressPhotoUpload({
elem: document.querySelector("#input"), //必传,上传图片的input元素
ratio: 0.3, //默认为0.1 压缩比
maxsize: 1024, //默认为1024,单位为kb 大于此值则做压缩操作
success: (e) => { //必传,成功后的回调函数,返回的参数是图片信息(对象)
// console.log(e);
$('#loading').hide();
// $("#bq-upload-img").attr("src", e.data).fadeIn();//给img标签渲染压缩后的图片
let bl = pubGoodsPage.convertBase64UrlToBlob(e.data);//将base64对象转为blob对象
var File = new window.File([bl], e.name, {
type: e.dataType,
lastModified: Date.now()
});//将blob对象转为文件对象
pubGoodsPage.uploadImage(File);//执行上传操作
}
});
} else {
// $("#bq-upload-img").attr("src", ImgFile);//给img标签渲染压缩后的图片
let file = document.getElementById("input").files[0];//获取表单文件对象
pubGoodsPage.uploadImage(file);//执行上传操作
}
}
},
//base64转64对象
convertBase64UrlToBlob(urlData) {
var bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], {type: 'image/png'});
},
//上传图片
uploadImage(para) {
//开始准备图片数据
let file = para;
let form = new FormData();
form.append("file", file);
//上传图片到后台
$.ajax({
type: "post",
url: bqUrl.pubwelUploadImg,
data: form,
dataType: 'json',
contentType: false,
processData: false,
beforeSend: function () {
$('#loading').show();
},
timeout: 60000,
success: function (res) {
$('#loading').hide();
if (res.result == 1) {
$("#input").attr("type", "text");
$("#input").attr("type", "file");
pubGoodsPage.pubImage.push(res.data.fileName);
} else {
console.log("上传图片失败!")
}
},
error: function (res) {
$('#loading').hide();
console.log("请求失败!");
mui.alert("网络错误,请刷新之后重试!", function () {
window.location.reload();
})
}
})
},
网友评论