preface

Silence for a long time, I came back, this time is about the small program direct aliyun problem. First of all, I would like to introduce the background of the project. This project needs to upload pictures. Just a few days ago, it connected with the browser to upload Ali Cloud OSS and used stsToken (temporary authorization). So take the opportunity to put the small program to the whole bar, but also include pictures before uploading watermark text.

Reference documentation

Alipay small program direct transmission practice

Micro channel small program direct transmission practice

After looking for a lot of articles, I found that the official documents are more reliable, more thorough understanding.

About data and dependencies

Our oss usage model: the backend creates THE RAM role, and the front end obtains the security token (stsToken) of a RAM role through the interface. This token can expire, and when it expires, a stsToken can be acquired again, avoiding the problem of acquiring a token for permanent use.

NPM install crypto-js NPM install js-base64 // Used for policy and signature processingCopy the code

The original

  • upload.js

    Import crypto from 'crypto-js' import {Base64} from 'js-base64' import {getOss} from '@/utils/utils.js' // random string function randomString(num) { const chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] let res = '' for (let i = 0; i < num; I++) {let id = math.ceil (math.random () * 35) res += chars[id]} return res} // calculate the signature. function computeSignature(accessKeySecret, canonicalString) { return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret)) } const date = new Date() date.setHours(date.getHours() + 1) const policyText = { 'expiration': Date.toisostring (), // Set the policy expiration time. 'conditions': [// limit upload size.  ['content-length-range', 0, 1024 * 1024 * 1024] ] } export function uploadFile({filePath, extensionName, fileType}) { return new Promise(async(resolve, reject) => { let oss = await getOss() const url = 'https://xxxxxx.xxxx.aliyuncs.com/' const policy = Encode (json.stringify (policyText)) // Policy must be a string of Base64. const signature = computeSignature(oss.credentials.accessKeySecret, Path + randomString(6) + +new Date() + extensionName // path + randomString + current timestamp + file format name uni.uploadFile({ 'url': url, // #ifdef MP_WEIXIN 'name': 'file', // #endif // #ifdef MP-ALIPAY 'fileType': FileType, // fileType supports image, video, audio (image/video/audio) 'fileName': 'file', // #endif 'filePath': FilePath, // filePath to be uploaded 'formData': {'key': fileName, // set filePath to be uploaded to OSS 'OSSAccessKeyId': oss.credentials.accessKeyId, signature, policy, success_action_status: '200', // The default upload success code is 204, which is set to 200 by Success_action_status. 'x-oss-security-token': oss.credentials.securityToken // stsToken }, 'success': (res) => {console.log(res.statuscode) // the default upload success statusCode is 204, which is success_action_status set to 200. If (res.statuscode == 200) {console.log(res, 'upload successfully ') resolve({url: Url + fileName})} else {console.log(res, 'upload else') reject(res)}}, 'fail': Err = > {the console. The log (err, 'upload failure) reject (err)}})})}Copy the code
  • Add watermarks before uploading images

    const addWaterMark = (that, ctx, filePath, height, width) => { return new Promise((resolve, reject) => { const padding = 200 const rotate = 35 const getRadian = (degree: number) => degree * Math.PI / 180 ctx.drawImage(filePath, 0, 0, width, height) ctx.translate(width / 2 * Math.tan(getRadian(rotate)), 0/0/0/0/0/0/0 SetFontSize (16) ctx.settextalign ('center') ctx.setFillStyle('#797878') let x = 20 let y = 20 let addingX = true const fillText = '20210305' while (y < height) { ctx.fillText(fillText, x, y) if (x > width) { x = 20 addingX = false } if (addingX) { x += padding } else { y += padding addingX = true } } ctx.draw(false, () => { uni.canvasToTempFilePath({ canvasId: ctx.canvasId, destWidth: width, destHeight: height, success: (res) => { let path = res.tempFilePath resolve(path) }, fail: (err) => { reject(err) } }, that) }) }) }Copy the code
    // upload.js
    export async function uploadWaterMarkImage ({ that, filePath, extensionName, ctx, height, width}) {
        ...
        let waterMarkFilePath = await addWaterMark(that, ctx, filePath, height, width)
        ...
    }
    Copy the code

conclusion

Touch fish for a long time, finally came back, will continue to more text, put their own use to the things on the top, as a summary of experience. The next article is about the Upload component encapsulated according to this method.

UNIAPP package upload component (add text watermark) direct to OSS