问题: 图片上传后保存的图片跟原图不一致,还要待研究
//选择图片
chooseImg(e) {
let that = this;
let imgs = this.data.imgs;
let imgsHidden = this.data.imgsHidden;
const token = wx.getStorageSync("jwt");
wx.request({
url: app.globalData.baseUrl + '/api/oss/frontend_sts_token',
method: 'get',
header: {
'content-type': 'application/json',
'Authorization': "Bearer " + token
},
success: res => {
wx.chooseImage({
count: 24, // 默认最多一次选择9张图
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res1) {
let tempFilePaths = res1.tempFilePaths;
that.setData({
sts_token_data: res.data.data
})
uploadImage({
filePath: tempFilePaths,
sts_token_data: that.data.sts_token_data,
success: function (res) {
imgs.push(app.globalData.imgUrl + res);
imgsHidden.push(res);
that.setData({
imgs,
imgsHidden
});
console.log(that.data)
wx.hideLoading();
},
fail: function (res) {
console.log("上传失败");
wx.hideLoading();
}
});
// that.getCanvasImg(0, 0, tempFilePaths);
},
})
}
})
},
//压缩并获取图片,这里用了递归的方法来解决canvas的draw方法延时的问题
getCanvasImg: function (index, failNum, tempFilePaths) {
let that = this;
let imgs = this.data.imgs;
let imgsHidden = this.data.imgsHidden;
// let imgsTemp = that.data.imgsTemp;
if (index < tempFilePaths.length) {
const ctx = wx.createCanvasContext('attendCanvasId');
wx.getImageInfo({
src: tempFilePaths[index],
success(res) {
let width = that.data.windowWidth / 750 * 500;
let height = res.height * width / res.width;
that.setData({
canvasW: width * 2, //宽度两倍
canvasH: height * 2 //高度两倍
})
ctx.drawImage(tempFilePaths[index], 0, 0, width, height);
// ctx.drawImage(tempFilePaths, 0, 0, width, height);
ctx.draw(true, function () {
index = index + 1;//上传成功的数量,上传成功则加1
wx.canvasToTempFilePath({
canvasId: 'attendCanvasId',
success: function success(res) {
console.log(res)
console.log("success")
// imgsTemp.push(res)
// that.setData({
// imgsTemp
// });
uploadImage({
filePath: [res.tempFilePath],
sts_token_data: that.data.sts_token_data,
success: function (res) {
imgs.push(app.globalData.imgUrl + res);
imgsHidden.push(res);
that.setData({
imgs,
imgsHidden
});
console.log(that.data)
wx.hideLoading();
},
fail: function (res) {
console.log("上传失败");
wx.hideLoading();
}
});
setTimeout(()=>{
that.getCanvasImg(index, failNum, tempFilePaths);
},800)
}, fail: function (e) {
console.log("fail")
failNum += 1;//失败数量,可以用来提示用户
setTimeout(() => {
that.getCanvasImg(index, failNum, tempFilePaths);
}, 1000)
}
});
});
}
})
}
},
参考: https://www.jb51.net/article/143226.htm
网友评论