


Simple encapsulation example for downloading multiple files in WeChat mini program
This article mainly introduces a simple encapsulation example for downloading multiple files in a WeChat applet. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Requirements
Need to generate a promotional image to share in Moments. This promotional image contains a QR code, 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 it returns the temporary path of the file, 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
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
url The network address of the downloaded file (requires WeChat applet background configuration, please refer to WeChat official documentation for specific configuration methods)
success The return parameter of the success callback is an object containing id, savedFilePath
fail The failure callback, download failure, and saving are all considered failures
/** * 下载保存一个文件 */ 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 configuring the server domain name in the WeChat applet. Please configure the server domain name in the applet background-settings-development settings-server domain name. For details, please refer to the WeChat official document
Encapsulate multiple file downloads and save
Multiple file downloads and saves. It is mandatory that all files must be downloaded successfully before the return is successful
Parameter: an object containing
urls download address array, supports multiple url downloads [url1, url2]
success The download is successful (all files must be downloaded successfully to be considered successful). Callback parameter map, key(id) -> value ({id,savedFilePath})
fail The download fails, as long as there is If a method fails, the call fails
/** * 多文件下载并且保存,强制规定,必须所有文件下载成功才算返回成功 */ 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"
and then call
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("下载失败"); } );
related Recommended:
Ajax simple encapsulation details #Simple encapsulation of some functions of the mysql module in php
The above is the detailed content of Simple encapsulation example for downloading multiple files in WeChat mini program. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Python provides the following options to open downloaded files: open() function: open the file using the specified path and mode (such as 'r', 'w', 'a'). Requests library: Use its download() method to automatically assign a name and open the file directly. Pathlib library: Use write_bytes() and read_text() methods to write and read file contents.

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

How to use PHP functions to upload and download attachments for sending and receiving emails? With the rapid development of modern communication technology, email has become an important way for people to communicate and transmit information in daily life. In web development, we often encounter the need to send and receive emails with attachments. As a powerful server-side scripting language, PHP provides a wealth of functions and class libraries that can simplify the email processing process. This article will introduce how to use PHP functions to upload and download attachments for sending and receiving emails. Email is sent first, we

How to use Laravel to implement file upload and download functions Laravel is a popular PHP Web framework that provides a wealth of functions and tools to make developing Web applications easier and more efficient. One of the commonly used functions is file upload and download. This article will introduce how to use Laravel to implement file upload and download functions, and provide specific code examples. File upload File upload refers to uploading local files to the server for storage. In Laravel we can use file upload

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

Nowadays, many applications allow users to upload and download files. For example, plagiarism detection tools allow users to upload a document file that contains some text. It then checks for plagiarism and generates a report that users can download. Everyone knows how to use inputtypefile to create a file upload button, but few developers know how to use JavaScript/JQuery to create a file download button. This tutorial will teach you various ways to trigger a file download when an HTML button or JavaScript is clicked. Use HTML's <a> tag and download attribute to trigger file download when the button is clicked. Whenever we give the <a> tag

How to use the Hyperf framework for file downloading Introduction: File downloading is a common requirement when developing web applications using the Hyperf framework. This article will introduce how to use the Hyperf framework for file downloading, including specific code examples. 1. Preparation Before starting, make sure you have installed the Hyperf framework and successfully created a Hyperf application. 2. Create a file download controller First, we need to create a controller to handle file download requests. Open the terminal and enter

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling
