WeChat Applet Development--Download Any File via Cloud Function

WeChat Applet Development--Download Any File via Cloud Function

1. Introduction to Cloud Development

WeChat applet developers are known to have many restrictions on applet development. When I was still a novice, the first level was stuck in HTTP requests without filed domain names. At that time, cloud development was not very long on the line, and there were not many people using it. I tried to contact cloud development and discovered the benefits of cloud development.(Freedom)

blog: WeChat Applet HTTP Access Link Solution

2. Applet file download restrictions

In addition to restrictions on access address, the WeChat applet also has restrictions on file download. As shown in the following figure, only resource server A, which is in the downloadFile domain name whitelist and has SSL access configured, can download resources normally by HTTPS.(Free egg pain, much criticized)

3. Cloud Function Download Any File Design

Still with the trust in cloud development, try using cloud functions for any file download, and the idea is illustrated below.

Two ways to download files through the cloud function described in the figure above

  1. Cloud functions act only as a data-transfer node, requesting resources to be converted into Buffer s and returned directly to the applet.
  2. Cloud functions act as memory, and download resources are stored in the cloud and returned to the applet-side fileID (replacing the download address).

4. Cloud function implementation

Request resource file returns Buffer through request header configuration.

const cloud = require('wx-server-sdk')
const request = require('request')
const fs = require('fs')
const path = require('path')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database(); //Initialize Cloud Database
exports.main = async (event, context) => {
  var url = event.url; //Download address, which should be passed by the front end, then downloaded by the cloud function
  var type = event.type; //type:'dump'(dump)'trans' (pass)
  var filename = event.filename;
  //File name needs to be uploaded by itself or substring intercepts url
  var options = {
    url: url,
    encoding: null,
    headers: {
      "content-type": "application/octet-stream",
    },
  };
  return new Promise(function (resolve, reject) {
    request(options, function (error, response, body) {
      if(type=='trans'){
          //relay
        resolve(body)
      }else{
          //dump
        resolve(
          cloud.uploadFile({
            cloudPath: 'tmp/'+filename,
            fileContent: body,
          })
        )
      }
    })
  })
}

5. Relay download method (not recommended for small files)

If the file reaches a certain volume, the following problems may occur:

Relay downloads have limitations on file size, which are easily exceeded due to the cloud function return limitations.However, for some kb files, this is recommended to reduce the time required for dump.

Relay download resources are written as follows:

   var _filename = 'Beautiful scenery.jpg';
   var _url = 'http://img.apisev.cn:8081/wechat/sk1.jpg';
    wx.cloud.callFunction({
      name:'transfile',
      data:{
        url:_url,
        filename:_filename,
        type:'trans'
      },
      success(res){
        console.log(res)
        const FileSystemManager = wx.getFileSystemManager();
        FileSystemManager.writeFile({
          filePath:wx.env.USER_DATA_PATH+"/"+_filename,
          data:res.result,
          encoding: 'binary',//Encoding, Binary
          success(tres){
            console.log(tres)
            //You can open a file based on filePath, here's an example of a picture
            var _filepath = wx.env.USER_DATA_PATH+"/"+_filename;
            wx.previewImage({
              urls: [_filepath],
            })
          },fail(tres){
            console.log(tres)
          }
        })
      },fail(res){
        console.log(res)
      }
    })

Run on real machine to successfully preview resource pictures.

6. Dump download method (recommended)

First, you can find the address of any picture resource in the Internet resources and call the cloud function.

var _filename = 'Beautiful scenery.jpg';
var _url = 'https://n.sinaimg.cn/sinacn20106/212/w2048h1364/20190828/cded-icuacsa3953451.jpg';
wx.cloud.callFunction({
      name:'transfile',
      data:{
        url:_url,
        filename:_filename,
        type:'dump'
      },
      success(res){
        console.log(res)
      },fail(res){
        console.log(res)
      }
 })

Return as follows:

Pictures were successfully saved to cloud storage.

7. Reference Documents

[1] FileSystemManager.writeFile(Object object)

Tags: encoding Database SSL SDK

Posted on Wed, 27 May 2020 20:53:43 -0400 by duclet