choseImg() {
let that = this;
that.isCrossImg = true;
uni.chooseImage({
count: that.count,
sizeType: ['compressed', 'original'],
sourceType: that.sourceType,
success: function(chooseImageRes) {
console.log("chooseImageRes", chooseImageRes);
let tempFilePaths = chooseImageRes.tempFilePaths; //上傳的圖片路徑
//判斷圖片上傳是否必須要橫圖,若需要則驗證
if (that.baseData.remote) {
tempFilePaths.forEach((item, index) => {
uni.getImageInfo({
src: item,
success: (res) => {
let canvasWidth = res.width; //圖片原始長寬
let canvasHeight = res.height;
if (canvasWidth <= canvasHeight) {
uni.showToast({
title: '請使用手機橫拍上傳圖片',
duration: 1000,
icon: 'none'
});
that.isCrossImg = false;
return;
}
},
complete: () => {
if (index == tempFilePaths.length - 1 && that.isCrossImg) {
that.appCompressImg(0, tempFilePaths);
}
}
})
})
} else {
that.appCompressImg(0, tempFilePaths);
}
}
})
},
//app壓縮圖片,由於這個操作是異步,所以需要遞歸,num記錄遞歸的次數是否等於數組長度用於程序的返回
appCompressImg(num, tempFilePaths) {
let that = this;
let index = tempFilePaths[num].lastIndexOf("."); //獲取圖片地址最后一個點的位置
let img_type = tempFilePaths[num].substring(index + 1, tempFilePaths[num].length); //截取圖片類型如png jpg
let img_yuanshi = tempFilePaths[num].substring(0, index); //截取圖片原始路徑
let d2 = new Date().getTime(); //時間戳
//壓縮圖片
plus.zip.compressImage({
src: tempFilePaths[num], //你要壓縮的圖片地址
dst: img_yuanshi + d2 + '.' + img_type, //壓縮之后的圖片地址(注意壓縮之后的路徑最好和原生路徑的位置一樣,不然真機上報code-5)
width: '800px',
height: 'auto'
},
function(e) {
//壓縮之后路徑轉base64位的
//通過URL參數獲取目錄對象或文件對象
plus.io.resolveLocalFileSystemURL(e.target, function(entry) {
// 可通過entry對象操作test.html文件
entry.file(function(file) { //獲取文件數據對象
var fileReader = new plus.io.FileReader(); // 文件系統中的讀取文件對象,用於獲取文件的內容
fileReader.readAsDataURL(file); //以URL編碼格式讀取文件數據內容
fileReader.onloadend = function(evt) { //讀取文件成功完成的回調函數
let base64 = evt.target.result; //拿到base64
that.$api.mainApi.uploadImageBase64({
base64Data: base64
}).then(res => {
if (res.data.code == 0) {
let url = that.$imgBaseUrl + res.data.data;
if (that.count == 1) {
that.$set(that.imgUrls, '0', url);
} else {
that.imgUrls.push(url);
}
if (num == tempFilePaths.length - 1) {
let data = {
comName: that.comName,
value: {
imgSubType: that.baseData.subType,
value: that.imgUrls
}
}
that.$emit("sendData", data);
return
} else {
//利用遞歸循環來實現多張圖片壓縮
that.appCompressImg(num + 1, tempFilePaths)
}
} else {
uni.showToast({
title: '圖片上傳失敗',
duration: 2000
});
}
})
}
})
})
},
function(error) {
console.log("Compress error!");
console.log(JSON.stringify(error));
}
);
},