Small program offers a wx. SaveImageToPhotosAlbum can save the image to the local, but the parameter filePath has the following details:

Image file path, can be temporary file path or permanent file path (local path), does not support network path

But what about base64 or buffer streams?

A recent requirement (described below) encountered this problem, note it.

OK, back to the point:

1, demand small program for each login user to generate a TWO-DIMENSIONAL code (or small program code), promote out, other users through scanning this two-dimensional code into the small program can know who is through the two-dimensional code into the.

2, after the analysis of the need to know the idea is probably: in the small program to generate a small program with the user’s unique identification of the TWO-DIMENSIONAL code (or small program code), and then saved to the local user for use.

3, start thinking clearly, start it, first check the document

  • Gets the small program codeThe document provides several generation methods, which can be selected by comparing their characteristics and combining with business scenarios. I use them herewxacode.getUnlimitedThere are two invocation methods: 1. HTTPS invocation. 2. The first method of cloud invocation requires the cooperation of back-end students and interactive acquisition with wechataccess_tokenThis is the interface call credentials. The second way, which is used in this paper, is called by the ability of wechat small program cloud development. There should be one in the root directory after cloud development is enabledcloudFunFolder, this is where the cloud functions are stored, right click on this folder and clickCreate a new Node.js cloud functionWhatever the name is, mine is createQrCode
  cloudFun
+ |- createQrCode
+   |- config.json
+   |- index.js
+   |- package.json
Copy the code

The file structure should now look like this.

// config.json

{
  "permissions": {
    "openapi": [
      "wxacode.getUnlimited"]}}Copy the code
// index.js // const cloud = require('wx-server-sdk'Cloud.init () // cloud function exports.main = async (event, event) context) => { try { const result = await cloud.openapi.wxacode.getUnlimited({ scene:'userId=123'// use userId as the unique identifier})returnresult; } catch (err) { throw err; }}Copy the code

Package. json is not modified by default.

Now that the cloud function is created, right click on the newly created createQrCode folder and click Upload and Deploy: Cloud Install dependencies.


The cloud function has been created above and is now ready to be used.

wx.cloud.init();
  wx.cloud.callFunction({
    name: 'createQrCode'Complete: res => {console.log(res)}})Copy the code

Here is the printed result as follows:

Res.result. buffer is the image of the small code that we get, just as a buffer stream and we want to save the image locally, but how to save the buffer? The above parameters of wechat save picture API only support file path. Look directly at the code:

wx.cloud.init();
  wx.cloud.callFunction({
    name: 'createQrCode'// The name of the cloud function complete: res => {const buffer = res.result.buffer; var manager = wx.getFileSystemManager(); manager.writeFile({ filePath: wx.env.USER_DATA_PATH +'/qucode.png',
        data: buffer,
        success: res => {
          wx.saveImageToPhotosAlbum({
            filePath: wx.env.USER_DATA_PATH + '/qucode.png',
            success: function () {
              wx.showToast({
                title: 'Saved successfully',
              })
            },
            fail: function (err) {
              console.log(err)
            }
          })
        }, fail: err => {
          console.log(err)
        }
     })
    }
  })
Copy the code

ArrayBufferToBase64 is just a way of getting the file manager from wx.getFilesystemManager and calling the writeFile method to write the file. Then call wx. SaveImageToPhotosAlbum is ok. Document FileSystemManager here. WriteFile

Where wx.env.USER_DATA_PATH is an environment variable in the applet and represents the user directory path in the file system

We can also convert buffer to base64 and call this method. The result is the same, except that the encoding is set to ‘base64’.

letbase64 = wx.arrayBufferToBase64(buffer); // Convert buffer to base64Copy the code

This saves the code locally, but remember that we have a parameter userId=123. How do I get this parameter? The onLaunch and onShow methods in app.js can accept an option.

App({
    onLaunch: function(options) {
        console.log(options, 'onLaunch')
    },
    
    onShow: function(options) {
        console.log(options, 'onShow')},... })Copy the code

options
Normal compilation mode
Compiled by TWO-DIMENSIONAL code

Choose to compile through the TWO-DIMENSIONAL code, select the picture you just saved, and then look at the printed information

As you can see, the parameters we just passed are in options.query.scene, but the content is formatted in escape format, so we can use decodeURIComponent to get the source parameters.

App({
    onLaunch: function(options) {
        console.log(decodeURIComponent(options.query.scene), 'onLaunch')
    },
    
    onShow: function(options) {
        console.log(options.query.scene, 'onShow')},... })Copy the code

You can see that the correct parameters have now been taken.

Give it a thumbs up if you think it helps.