最近在做一个小程序涉及到用户输入文字和上传图片,这小程序有规定需要对用户输入的内容做安全检测,所以会用到需要用到官方openapi接口['security.msgSecCheck-v1','security.imgSecCheck']
上篇文章中讲到通过呼叫资源方的云函数调用这两个接口
本篇文章主要就说下用户选中图片上传到资源方云储存中通过fileID再进行安全检测
首先还是实例化共享云环境:
async onLoad(options) {
/**注册共享云环境 */
that.data.share_cloud=new wx.cloud.Cloud({
resourceAppid:app.globalData.resourceAppid,//资源方appid
resourceEnv:app.globalData.resourceEnv //云环境名称
})
//注意:必须要等init完成,不然会报错,所以这里用了个异步等待
await that.data.share_cloud.init()
}
每次用共享云环境的时候都需要通过资源方的appid和环境名称 new 一个wx.cloud.Cloud对象,表示需要获取或更新这个云环境的资源。
var share_cloud= that.data.share_cloud
//选择照片
wx.chooseMedia({
count: 1, // 默认9
mediaType:['image'],
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
camera:'front',
success(res) {
var localPicPath=res.tempFiles[0].tempFilePath;
that.setData({is_upload_loading:true,upload_loading_msg:'检测中',})
//照片上传到云储存获取fileID
share_cloud.uploadFile({
cloudPath: '云储存文件保存位置',
filePath: localPicPath,
success(res){
//图片检测参数
var forData={
type:"security",
func:'security.imgSecCheck',
fileID:res.fileID
}
//通过fileID检测图片是否违规
that.callDreamDrawing_Security(share_cloud,forData).then(res => {
if(res.result&&res.result.errCode!=0){
that.setData({
is_upload_loading:false,
upload_loading_msg:'照片含有违规风险,请更换一张照片'
})
//图片未通过检测,删除图片
that.deleteCloudImage(fileId)
}else{
//图片通过检测可进行下一步
//需要注意,上传到共享环境返回fileID不能渲染到页面上,这里需要渲染的话直接使用localPicPath 即可
}
}).catch(err =>{
console.log(err)
})
},fail(err){
wx.hideLoading()
wx.showToast({
title: '上传失败',
icon:'error',
duration:1500
})
console.log(err,'uploadFileErr')
}
})
}
})
其实上传图片到共享环境和正常非共享环境基本上差不多
区别在于:上传到非共享环境时直接 wx.cloud.uploadFile 即可,而上传到共享环境时需要new一个wx.cloud.Cloud对象
共享环境还有一点注意的就是不能直接使用使用资源方的fileID渲染到页面上,如有需求可以通过getTempFileURL获取文件的https链接,代码如下
/**通过fileID获取 https真实链接 */
share_cloud.getTempFileURL({
fileList: [{
fileID: 'fileID',
maxAge: 60 * 60, // 过期时间1小时
}]
}).then(res => {
console.log(res.fileList)
}).catch(error => {
console.log(error,'getTempFileURL_error')
})