哈哈,花了点时间,实现不用npm),实现imgSecCheck,又精简了程序包,这不美吗
先看效果
不废话,上代码就完事了
云函数端:
// 云函数入口文件
const cloud = require('wx-server-sdk')
const request = require('request') //node.js原生方法,不用npm
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
try {
const qs = await new Promise((resolve, reject) => {
//encoding: null,这个是关键,否则返回字符串而不是二进制数组
request({method: 'GET',url:event.url,encoding: null}, (error, response, body) => {
if (error) {
reject(error)
} else {
console.log('body',body)
resolve(body)
}
})
})
const result = await cloud.openapi.security.imgSecCheck({
media: {
contentType: 'image/png',
value: qs
}
})
if (result && result.errCode.toString() === '87014') {
return { code: 500, msg: '内容含有违法违规内容', data: result }
} else {
return { code: 200, msg: '内容ok', data: result }
}
} catch (err) {
// 错误处理
if (err.errCode.toString() === '87014') {
return { code: 500, msg: '内容含有违法违规内容', data: err }
}
return { code: 502, msg: '调用imgSecCheck接口异常', data: err }
}
}
小程序端:
wx.chooseImage({
count: imgMaxNum-imgList.length,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
console.log(res)
const tempFiles = res.tempFiles;
wx.showLoading({
title: '导入中',
})
that.data.fabuing = true
tempFiles.forEach( (items,id) => {
console.log(items.size/1024)
console.log(items)
// 官方说云调用imgSecCheck 限1M,但我实测超过450KB就很容易报错
if (items && items.size <= 450*1024) {
// 此步关键,图片先转buffer
console.log(items.path)
wx.getFileSystemManager().readFile({
filePath: items.path,
success: res => {
var buff = res.data
console.log(buff)
wx.cloud.callFunction({
name: 'imgSecCheck',
data: {
url:wx.cloud.CDN(buff) //将CDN 上传buffer,在向云函数传入零时url
}
})
.then(res => {
console.log(res);
let {errCode} = res.result.data;
switch (errCode) {
case 87014:
//此时说明图片内容不过
var index = list.findIndex(cur=>cur.path==items.path)
that.setData({
['imgList['+index+'].size']: 0
})
break;
case 0:
break;
default:
break;
}
})
.catch(err => {
console.error(err);
})
}
})
}
if(id==tempFiles.length-1){
wx.hideLoading()
that.data.fabuing = false
var list = imgList.concat(tempFiles)
that.setData({
imgList: list
})
console.log(list)
}
})
}
})
代码是没问题,但坑的是开发者工具里,云函数怎么都获取不到图片二进制信息,真机就没问题