Home  >  Article  >  Web Front-end  >  Multi-file download encapsulation use of WeChat applet

Multi-file download encapsulation use of WeChat applet

php中世界最好的语言
php中世界最好的语言Original
2018-03-23 09:54:422366browse

This time I will bring you the multi- file download package usage of WeChat mini program. What are the precautions when using the multi-file download package of WeChat mini program? The following is a practical case. , let’s take a look.

Requirements

Need to generate a promotional picture to share in Moments. This promotional picture contains a QR code, including different background images and Different text. For this kind of image generation, we considered using server-side generation, but this would consume more server performance, so we finally decided to use local generation.

First of all, the mini program has a limitation. The package cannot be larger than 2m, and we may have multiple background images, so we plan to put the background images and QR code images on the server, which can reduce the size of the mini program package. You can also flexibly switch background images.

When drawing a shared image, you can directly use the Internet address, but we encountered a problem and may not be able to generate the image, so we need to download the image file.

WeChat has an API for downloading files, but the temporary path of the file is returned, which can only be used normally during the current startup of the mini program. If you need to save it persistently, you need to actively call wx.saveFile before you can download the file. The applet can be accessed the next time it is started.

So we first encapsulate the downloaded file and the saved file

Encapsulate the download and save a file

This method is relatively simple

Parameter: an object, containing

  1. id. The id of the file that needs to be downloaded. If not passed, the default is the download url. The reason why the id is needed is because we need to download multiple files and can distinguish them. What is downloaded is a file

  2. url The network address of the downloaded file (requires WeChat applet background configuration, please refer to WeChat official documentation for specific configuration methods)

  3. success The success callback return parameter is an object containing id, savedFilePath

  4. ##fail Failure callback, download failure, and saving are all considered failures

  5. /**
     * 下载保存一个文件
     */
    function downloadSaveFile(obj) {
      let that = this;
      let success = obj.success;
      let fail = obj.fail;
      let id = "";
      let url = obj.url;
      if (obj.id){
        id = obj.id;
      }else{
        id = url;
      }
      // console.info("%s 开始下载。。。", obj.url);
      wx.downloadFile({
        url: obj.url,
        success: function (res) {
          wx.saveFile({
            tempFilePath: res.tempFilePath,
            success: function (result) {
              result.id = id;
              if (success) {
                success(result);
              }
            },
            fail: function (e) {
              console.info("保存一个文件失败");
              if (fail) {
                fail(e);
              }
            }
          })
        },
        fail: function (e) {
          console.info("下载一个文件失败");
          if (fail) {
            fail(e);
          }
        }
      })
    }
Using the download method (wx.downloadFile(obj)) requires WeChat

mini program configurationserver domain name. Please configure the server domain name in the mini program background-settings-development settings-server domain name. For details, please refer to WeChat official document

Encapsulation of downloading and saving multiple files

Downloading and saving multiple files, it is mandatory that all files must be downloaded successfully before the return is successful

Parameter: an object, containing

  1. urls download address array, supports multiple url downloads [url1, url2]

  2. success download successfully ( All files must be downloaded successfully to be considered successful) Callback parameter map, key(id) -> value ({id,savedFilePath})

  3. fail Download fails, as long as one method fails The call failed

  4. /**
     * 多文件下载并且保存,强制规定,必须所有文件下载成功才算返回成功
     */
    function downloadSaveFiles(obj) {
      // console.info("准备下载。。。");
      let that = this;
      let success = obj.success; //下载成功
      let fail = obj.fail; //下载失败
      let urls = obj.urls; //下载地址 数组,支持多个 url下载 [url1,url2]
      let savedFilePaths = new Map();
      let urlsLength = urls.length; // 有几个url需要下载
      for (let i = 0; i < urlsLength; i++) {
        downloadSaveFile({
          url: urls[i],
          success: function (res) {
            //console.dir(res);
            //一个文件下载保存成功
            let savedFilePath = res.savedFilePath;
                    
            savedFilePaths.set(res.id, res);
            console.info("savedFilePath:%s", savedFilePath);
            if (savedFilePaths.size == urlsLength) { //如果所有的url 才算成功
              if (success){
                success(savedFilePaths)
              }
              
            }
          },
          fail: function (e) {
            console.info("下载失败");
            if (fail) {
              fail(e);
            }
          }
        })
      }
    }
Complete download.js file

/**
 * 下载管理器
 * Created by 全科 on 2018/1/27.
 */
/**
 * 下载保存一个文件
 */
function downloadSaveFile(obj) {
  let that = this;
  let success = obj.success;
  let fail = obj.fail;
  let id = "";
  let url = obj.url;
  if (obj.id){
    id = obj.id;
  }else{
    id = url;
  }
  // console.info("%s 开始下载。。。", obj.url);
  wx.downloadFile({
    url: obj.url,
    success: function (res) {
      wx.saveFile({
        tempFilePath: res.tempFilePath,
        success: function (result) {
          result.id = id;
          if (success) {
            success(result);
          }
        },
        fail: function (e) {
          console.info("保存一个文件失败");
          if (fail) {
            fail(e);
          }
        }
      })
    },
    fail: function (e) {
      console.info("下载一个文件失败");
      if (fail) {
        fail(e);
      }
    }
  })
}
/**
 * 多文件下载并且保存,强制规定,必须所有文件下载成功才算返回成功
 */
function downloadSaveFiles(obj) {
  // console.info("准备下载。。。");
  let that = this;
  let success = obj.success; //下载成功
  let fail = obj.fail; //下载失败
  let urls = obj.urls; //下载地址 数组,支持多个 url下载 [url1,url2]
  let savedFilePaths = new Map();
  let urlsLength = urls.length; // 有几个url需要下载
  for (let i = 0; i < urlsLength; i++) {
    downloadSaveFile({
      url: urls[i],
      success: function (res) {
        console.dir(res);
        //一个文件下载保存成功
        let savedFilePath = res.savedFilePath;                
        savedFilePaths.set(res.id, res);
        console.info("savedFilePath:%s", savedFilePath);
        if (savedFilePaths.size == urlsLength) { //如果所有的url 才算成功
          if (success){
            success(savedFilePaths)
          }          
        }
      },
      fail: function (e) {
        console.info("下载失败");
        if (fail) {
          fail(e);
        }
      }
    })
  }
}
module.exports = {
  downloadSaveFiles: downloadSaveFiles
}

Use

First import

import download from "download.js"
callafter

let url1 = 'https://xcx.upload.utan.com/article/coverimage/2018/01/25/eyJwaWMiOiIxNTE2ODU2Nzc0Njk3OCIsImRvbWFpbiI6InV0YW50b3V0aWFvIn0=';
let url2 = 'https://xcx.upload.utan.com/article/coverimage/2018/01/26/eyJwaWMiOiIxNTE2OTcyNDg0NDUzOSIsImRvbWFpbiI6InV0YW50b3V0aWFvIn0=';
download.downloadSaveFiles({
  urls: [url1, url2],
  success: function (res) {
    // console.dir(res);
   
    console.info(res.get(url2).savedFilePath)
  },
  fail: function (e) {
    console.info("下载失败");
  }
);
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Angular2 parent-child component communication method

Summary of jQuery code optimization method

How to deal with incomplete page display in 360 browser compatibility mode

The above is the detailed content of Multi-file download encapsulation use of WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn