小程序有【上传】功能,需要对内容进行信息安全校验。如果没有安全校验,会被审核拒绝的。
安全校验可以使用小程序提供的官方接口: 图片内容安全接口文档。
有三种调用方式:
- HTTPS 调用
- 云调用
- 增强调用(加强版)
我选择的是云调用。
使用云调用碰到的问题
云函数在接收来自云调用的 Buffer 数据,需要用 Buffer.from 方法将 string 类型转成 Buffer 类型。
// 云函数
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
exports.main = async (event, context) => {
try {
const result = await cloud.openapi.security.imgSecCheck({
media: {
contentType: event.contentType,
value: Buffer.from(event.value) // string 类型转为 Buffer 类型
}
})
return result
} catch (err) {
return err
}
}
图片内容安全接口,对图片大小和尺寸是有限制的(图片大小限制:1M,图片尺寸不超过 750px x 1334px),所以在调用接口前需要图片进行处理。
wx.chooseImage({
count: 1,
sizeType: ["original", "compressed"],
sourceType: ['album', 'camera'],
success: res => {
const src = res.tempFilePaths[0]
const that = this
const fm = wx.getFileSystemManager()
wx.getImageInfo({
src,
success(img) {
const width = 100
const height = width * img.height / img.width
const ctx = wx.createCanvasContext('myCanvas')
ctx.drawImage(img.path, 0, 0, width, height)
ctx.draw(false, setTimeout(function(){
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
width,
height,
destWidth: width,
destHeight: height,
success: function (res) {
fm.readFile({
filePath: res.tempFilePath,
success(data) {
wx.cloud.callFunction({
name: 'imgSecCheck',
data: {
value: data.data,
contentType: 'image/png',
}
})
.then(result => {
if (result.result.errCode === 0) {
// 图片通过校验
} else if (result.result.errCode === 87014) {
// 图片未通过校验
} else {
// 其他错误
}
})
.catch(err => {
console.log(err)
})
},
fail() { }
})
},
fail: function () { }
})
},100))
},
fail() { }
})
},
});