大家好,我是前端发现者https://blog.csdn.net/Smell_rookie,是一名页面仔工程师,我会不定时在CSDN更新我的博客,有兴趣的可以点个关注来逛逛我的主页。
写这个需求时网上搜索看到的文章不计其数,很多“缺斤少两”,今天做个总结吧。
由于签名计算放在前端会暴露 SecretId 和 SecretKey,我们把签名计算过程放在后端实现,前段通过 ajax 向后端获取签名结果,正式部署时请再后端加一层自己网站本身的权限检验。
去到这里下面地址下载文件到项目的utils文件夹下。https://github.com/tencentyun/cos-wx-sdk-v5https://github.com/tencentyun/cos-wx-sdk-v5
在需要执行上传操作的js文件复制如下代码:
- const COS = require('./cos-wx-sdk-v5.js')
-
- // 初始化腾讯云存储
- const commonCos = new COS({
- // ForcePathStyle: true,
- // 如果使用了很多存储桶,可以通过打开后缀式,减少配置白名单域名数量,请求时会用地域域名
- FileParallelLimit: 40, //同一个实例下上传的文件并发数,默认值3
- ChunkParallelLimit: 40, //同一个上传文件的分块并发数,默认值3
- //获取签名的回调方法
- getAuthorization: (options, callback) => {
- // 异步获取临时密钥
- http.getRequest('/small/small/getTempScert', {
- bucket: options.Bucket,
- region: options.Region,
- }, res => {
- let credentials = res.data.credentials
- if (!credentials) return console.error('credentials invalid')
- callback({
- TmpSecretId: credentials.tmpSecretId,
- TmpSecretKey: credentials.tmpSecretKey,
- XCosSecurityToken: credentials.sessionToken,
- // 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
- StartTime: res.data.startTime, // 时间戳,单位秒,如:1580000000
- ExpiredTime: res.data.expiredTime, // 时间戳,单位秒,如:1580000900
- })
- })
- }
- })
-
-
- // 上传图片 flag:1 需要校验是否需要水印 -1 不校验、不使用水印
- const commonUploadImg = async (name, flag = -1, classId = null) => {
- return new Promise((resolve) => {
- wx.chooseImage({
- count: 9,
- sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
- sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
- success: async (res) => {
- wx.showLoading({
- title: '上传中...',
- icon: 'loading',
- })
- let filenameList = []
- let filePathList = []
- if (res.tempFiles.length) {
- let tempFile = res.tempFiles
- let countNum = 0
- let waterResult = null
- if (flag == 1) {
- /**获取水印信息*/
- waterResult = await getClassInfoIfWaterMark({
- classId: classId,
- homeWorkId: name
- })
- }
- for (let temp of tempFile) {
- // 这里对图片校验-传入压缩后的图片
- const result = true
- if (result) {
- if (temp.size > 10485760) {
- wx.hideLoading()
- wx.showToast({
- title: `图片最大可以上传${10485760/1024/1024}M`,
- icon: 'none',
- duration: 1500
- })
- } else {
- const filePath = temp.path
- const tempDate = new Date()
- const createPath = tempDate.getFullYear() + "" + utils.formatNumber((tempDate.getMonth() + 1)) + "" + utils.formatNumber(tempDate.getDate()) + "/"
- const filename = createPath + name + '/' + filePath.substr(filePath.lastIndexOf('/') + 1)
- let fileId = filePath.substr(filePath.lastIndexOf('/') + 1)
- const wxfs = wx.getFileSystemManager()
- let ruleValue = `imageMogr2/format/jpg/interlace/1/rquality/60`
- let rule = {
- "is_pic_info": 0,
- "rules": [{
- "fileid": `${fileId}`,
- "rule": ruleValue
- }]
- }
- if (flag == 1) {
- if (waterResult && waterResult.ifWaterMark) {
- let info = `${waterResult.waterFormat}`
- let waterInfo = utils.Base64.encode(info)
- let fontColor = utils.Base64.encode(waterResult.waterColor || '#09ff00')
- let waterPosition = waterResult.waterPosition || 'center'
- let waterRangle = waterResult.waterRangle || 0
- let water = `watermark/2/text/${waterInfo}/font/c2ltaGVp6buR5L2TLnR0Zg/fill/${fontColor}/fontsize/50/gravity/${waterPosition}/degree/${waterRangle}/dissolve/100`
- rule.rules[0].rule = `${ruleValue}|${water}`
- }
- }
- wxfs.readFile({
- filePath: filePath,
- success(res) {
- commonCos.putObject({
- Bucket: 'img-work-1304215329',
- Region: 'ap-beijing',
- Key: filename,
- Body: res.data,
- Headers: {
- // 通过 数据万象的压缩自定义规则 style/uploadStyle
- // 'Pic-Operations': `{"is_pic_info": 0, "rules": [{"fileid": "${fileId}","rule": "style/uploadStyle"}]}`,
- 'Pic-Operations': `${JSON.stringify(rule)}`
- },
- }, function (err, data) {
- if (data && data.statusCode == 200) {
- countNum++
- filenameList.push(filename)
- filePathList.push(filePath)
- if (countNum == tempFile.length) {
- wx.hideLoading()
- let obj = {
- filenameList,
- filePathList
- }
- resolve(obj)
- }
- }
- })
- }
- })
- }
- }
- }
- }
- },
- fail() {
- wx.hideLoading()
- }
- })
- })
- }
-
-
持久化处理图片的规则可参考如下: