小程序共享环境上传图片到资源方获取fileID

最近在做一个小程序涉及到用户输入文字和上传图片,这小程序有规定需要对用户输入的内容做安全检测,所以会用到需要用到官方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')
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值