使用小程序的云函数实现图片上传至云服务器
云函数代码
// 云函数入口文件
const cloud = require('wx-server-sdk');
const utility = require('utility');
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
try{
return await cloud.uploadFile({
fileContent: new Buffer(event.fileContent, 'base64'),
cloudPath: utility.md5(String(Math.random())) // 使用随机文件名
})
}catch(e){
return e
}
}
小程序代码
chooseImage(){
const that=this;
wx.chooseImage({
count:1,
success(res) {
const path=res.tempFilePaths[0];
// 就文件转码为base64
const fileContent = wx.getFileSystemManager().readFileSync(path,'base64');
wx.cloud.callFunction({
name:'uploadFile',
data:{
fileContent
}
}).then(res=>{
const {result}=res;
that.setData({
uploadImg: result.fileID
});
})
},
})
},