openapi.security.imgSecCheck调用需要传参数media
media格式:
{contentType:"image/png",value:Buffer}
但是小程序前端是基于es开发,并不存在Buffer类型,而云函数是基于nodejs开发 ,确实存在Buffer类型,故实现方案如下:
将图片上传至云存储,在云函数中根据fileID下载得到返回数据中的fileContent,就可以作为buffer传参去校验非法图片了,实现代码如下:
云函数imgSecCheck代码
exports.main = async (event, context) => { const fileID = event.fileID const res = await cloud.downloadFile({ fileID: fileID, }) const buffer = res.fileContent try { var result = await cloud.openapi.security.imgSecCheck({ media: { contentType:event.contentType, value: buffer } }) return result } catch (err) { return err }}
小程序调用:
wx.cloud.uploadFile({ cloudPath, filePath, success: res => { console.log('[上传文件] 成功:', res) wx.cloud.callFunction({ name: 'imgSecCheck', data: { contentType: contentType, fileID: res.fileID } }).then(res => { console.log("检测结果", res.result); if (res.result.errCode == 0) { wx.showToast({ icon: 'none', title: '图片正常', }) } else { wx.showToast({ icon: 'none', title: '图片含有违法信息,请换张说明图', }) } }) }, fail: e => { console.error('[上传文件] 失败:', e) } })