upload() {
const promises = this.fileList3.map((item, index) => {
return new Promise((resolve, reject) => {
wx.compressImage({
src: item.url, // 图片路径
quality: 10, // 压缩质量
success: res => {
// 将压缩后的图片转换成 base64 编码
wx.getFileSystemManager().readFile({
filePath: res.tempFilePath,
encoding: 'base64',
success: res => {
// 调用云函数上传图片
wx.cloud.callFunction({
name: 'addarticleImages',
data: {
image: res.data // 图片的 base64 编码
},
success: res => {
resolve(res.result);
},
fail: error => {
reject(error);
}
});
},
fail: error => {
reject(error);
}
});
},
fail: error => {
reject(error);
}
});
});
});
Promise.all(promises).then(results => {
console.log(results);
}).catch(error => {
console.log(error);
});
},
微信云函数
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
// 云函数入口函数
const db = cloud.database()
const articleImages = db.collection('articleImages')
exports.main = async (event, context) => {
const image = event.image
const result = {}
try {
const res = await cloud.uploadFile({
cloudPath: 'articleImages/' + Date.now() + '.png',
fileContent: Buffer.from(image, 'base64')
})
const fileID = res.fileID
const fileURL = res.fileID
await articleImages.add({
data: {
fileID,
fileURL
}
})
result.fileID = fileID
result.fileURL = fileURL
} catch (error) {
console.log(error)
return error
}
return result
}